Hello Monks,
Am completely new at perl programming;
I am trying to count the occurence of a string "abc" in a flat file (data.txt) of following structure and return the count and the matching lines.
_data.txt_
abc:AB CD:100
def:DE FG:101
ghi:GH IJ:102
abc:AB CD:100
ghi:GH IJ:103
I am able to grep the matching lines for string "abc" using the below code, although i read that using grep is not advisable for huge files.
my $file='source_data\data.txt';
open FILE, $file or die "FILE $file NOT FOUND - $!\n";
while (<FILE>){
chop $_;
my ($a, $b, $c) = split /:/, $_;
my $r = [$a, $b, $c];
my @arr = $r->[0];
my @matches = grep $_ eq "abc", $arr[0];
foreach my $i (@matches) {
print $_."\n";
}
}
_ouput_
abc:AB CD:100
abc:AB CD:100
How can I get the count of matching lines?
Seeking your kind advise.
--new@perl
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.