in reply to Re^2: search pattern with digits
in thread search pattern with digits
Thanks for supplying the code and the sample log file. I saved the log file as 'test.txt' and ran your code. The subroutine returns an array of three undefined values, one for each of the first three search phrases, after which the text file is exhausted, so nothing (not even an undef array entry) is returned for the final search phrase.
The code is way too busy. You don't need to read a file into an array - you can just iterate one line at a time with while <$inFH>. You almost never to use an array index.
Finally, if your problem is to extract the number from the matching line wherever the number may be, why don't you just use /(\d+)/ to extract the number after you have matched the search phrase?
#!/usr/bin/perl use strict; use warnings; sub search_phrase { my ( $inFile, @phrases ) = @_; open my $inFH, q{<}, $inFile or die qq{open: $inFile: $!\n}; my $line; PHRASE: foreach my $phrase ( @phrases ) { my $rxPhrase = qr{\Q$phrase\E}; # keep reading down the file while ($line = <$inFH>) { # when one phrase matches, jump to the next next PHRASE if $line =~ /$rxPhrase/; } # end of file, and we haven't matched the last phrase return; } # We have just matched the last phrase. # The number we want is somewhere in $line. my ($number) = $line =~ /(\d+)/; return $number; } my $file_n = "test.txt"; my $phrase1 = "total rows rejected:"; my $phrase2 = "total rejected recors:"; my $phrase3 = "rows rejected for sub"; my $result = search_phrase($file_n, $phrase1, $phrase2, $phrase3); if (defined $result) { print "search_phrase subroutine found $result\n" } else { print "search_phrase subroutine didn't find a number." }
With your sample data, this returns
search_phrase subroutine found 390
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: search pattern with digits
by mercuryshipz (Acolyte) on Feb 15, 2008 at 16:23 UTC |