test.txt
total Laptops produced: 60
total cpu sold: 57
total mice produced: 40
total cpu sold: 45
total Laptops produced: 68
total mice produced: 48
total cpu sold: 51
total printers produced: 19
total monitors produced: 149
76 wireless cards produced
#!/usr/bin/perl
#
use strict;
use warnings;
use List::Util q{first};
sub search_phrase{
my ( $inFile, @phrases ) = @_;
my $lastPhrase = $phrases[ -1 ];
open my $inFH, q{<}, $inFile
or die qq{open: $inFile: $!\n};
my @lines = <$inFH>;
close $inFH or die qq{close: $!\n};
foreach my $phrase ( @phrases )
{
my $rxPhrase = qr{\Q$phrase\E};
my $lineNo =
first { $lines[ $_ ] =~ $rxPhrase } 0 .. $#lines;
unless ( defined $lineNo )
{
print qq{$phrase: not found in sequence\n};
next;
}
print qq{$1\n}
if $lines[ $lineNo ] =~ m{\Q$lastPhrase\E\s*(\d+)};
$lineNo ++;
splice @lines, 0, $lineNo;
}
}
$file_n = "test.txt";
$phrase1 = "total Laptops produced:";
$phrase2 = "total monitors produced:";
$phrase3 = "total cpu sold:";
&search_phrase($file_n, $phrase1, $phrase2, $phrase3);
the scripts works great....
i have changed this as a function
but a few more additions John
i have updated a line in test.txt
1. the return number which we want could be even at the beginning of the line also.
2. If the last phrase is not found it has to return -1 as the value
3. one more thing is if the same phrase is passed twice, it has return the last phrase's value.
For eg.
$phrase1 = "total cpu sold:";
$phrase2 = "total mice produced:";
$phrase3 = "total cpu sold:";
phrase3 's value has to be returned not both...
for example in our file
45 is to be returned, not both (57 and 45)
3. Could u add some comments if possible, to make it clear.
thanks a lot,
Mercury.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.