Quantifiers - Greedy and Non-Greedy: Learn Perl By Doing It, Part 9

Quantifiers in regular expressions let you specify how many characters you want to match. You can use quantifiers to specify exact numbers of characters, but the most important distinction is between greed and non-greedy quantifiers.



 
use strict;
use warnings;

$|=1;

sub main {
    my $file = 'C:tutorialperlmymanjeeves.txt';
    
    open(INPUT, $file) or die("Input file $file not found.n");
    
    while(my $line = <INPUT>) {
        
        # * matches zero or more of the preceding character; e.g.
        # d* matches zero or more d's 7* zero or more 7's, etc.
        # .* matches zero or more of any character, as many as possible
        # .*? matches zero or more of any character, as few as possible
        

        if($line =~ /(s.*?n)/) {
            print "$1n";
        }
    }

    close(INPUT);
}

main();