Writing Files and Replacing Text: Learn Perl By Doing It, Part 6

How to write and create files in Perl, and how to do a find-and-replace using regular expressions. Once we know how to read files and how to write files, we can read in one file, replace or correct text in it, and write it to another file. Which is very handy.



 
use strict;
use warnings;

$|=1;

sub main {
    
    # open $input for reading
    my $input = 'C:tutorialperlmymanjeeves.txt';
    open(INPUT, $input) or die("Input file $input not found.n");
    
    # open $output for writing
    my $output = 'output.txt';
    open(OUTPUT, '>'.$output) or die "Can't create $output.n";
    
    # Read the input file one line at a time.
    while(my $line = <INPUT>) {
        
        # If this line has the word "egg" in it, write it
        # to the output file, otherwise ignore it.
        # b matches the edges (boundaries) of words.
        if($line =~ /beggb/) {
            $line =~ s/hen/dinosaur/ig;
            print OUTPUT $line;
        }
    }

    close(INPUT);
    close(OUTPUT);

    close(OUTPUT);
}

main();