in reply to problem printing message if search item is not found
Besides the things already pointed out, there are some other issues with your script which may be problematic.
You are slurping the entire file into an array all at once. That isn't a problem for small files but if they start to hit a couple of MB, it may cause heavy swapping and out-of-memory errors. Better to process the file a bit at a time.
Also, since the file is being searched line by line, you can't search on strings that cross newlines.
A fairly simple fix to both of these is to process the file in paragraph mode. (What I am using below isn't true paragraph mode since that makes it much harder to keep track of line numbers, but it is a good approximation.)
############################################################### use warnings; use strict; my $fsearch = 'filename.txt'; print "\nEnter a string to search for:>"; my $search = <STDIN>; chomp $search; open my $TEXTFILE, '<', $fsearch or die "\nCan't open $fsearch $!\n"; $/ = "\n\n"; my ($linecount, $count) = (0,0); while (my $paragraph = <$TEXTFILE>) { while ($paragraph =~ /([^\n]*?($search)([^\n]*))/mig) { $count++; my $linenumber = $linecount + substr($paragraph, 0, $-[0]) =~ tr/\n/\n/ + 1; print "\n'$2' found on line #$linenumber\n\n"; print "$1\n", '-' x 79; pos $paragraph -= length $3; } $linecount += $paragraph =~ tr/\n/\n/; } print "\nThe string '$search' was ", ($count ? "found $count times" : "not found"), " in $fsearch"; ###############################################################
Notice that since the search term is not quotameta-ed you can search for strings like "\bto[ \n]be\b" (to be across a newline) or "\b\w*gh\w*\b" (words containing 'gh') as well as absolute strings like "again" or "match".
|
|---|