# File: file3.pl # Title: Find pattern in a file. Print the lines where it finds the pattern # Author: Mihaela Malita # Here is the file mary.txt: # Mary had a little lamb, # It's fleece was white as snow. # And everywhere that Mary went # The lamb was sure to go.... # Name of file? mary.txt # Find pattern? l..b # means a word with 4 letters start with l ends with b # Lines where pattern is found: # 1 Mary had a little lamb, # 4 The lamb was sure to go. # 8 To see a lamb at school. use strict; # all variables have to be declared with my use warnings; # gives warnings (same as >perl -w file3.pl ) my $filename; print "Name of the file (mary.txt)? "; $filename = ; chop($filename); #read from keyboard unless (open(IN,"$filename")) { #check if the file exists print "No file with such a name!"; exit; } my $p; #declare variable with pattern (it can be just a word!) print "Find pattern? "; $p = ; chop($p); print "Lines where the pattern $P is found:\n"; my $line; # the line of the text my $i = 0; # counts the lines while ($line = ) { #reads line by line the text file until End Of File (EOF) $i = $i + 1; if ( $line =~ /$p/ ) { #prints lines with the pattern (regular expr) print "$i\t\t$line"; } } close IN; exit;