Reading Files and Beginning Regular Expressions: Learn Perl By Doing It, Part 5

How to read files in Perl, and also the start of an introduction to regular expressions. Regular expressions can be used in pretty much every programming language these days, and stuff you learn about "regex" in Perl will also work, with minor variations, in other programming languages.



 
use strict;
use warnings;

$|=1;

sub main {
    my $file = 'C:tutorialperlmymanjeeves.txt';
    
    # Either successfully open the file or else die (stop the program)
    open(INPUT, $file) or die("Input file $file not found.n");
    
    # Read each line from the file, one line at a time.
    while(my $line = <INPUT>) {
        if($line =~ / egg /) {
            print $line;
        }
    }

    close(INPUT);
}

main();