Beefy Boxes and Bandwidth Generously Provided by pair Networks Cowboy Neal with Hat
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Better way of doing!

by Laurent_R (Priest)
on Aug 12, 2013 at 16:46 UTC ( #1049147=note: print w/ replies, xml ) Need Help??


in reply to Better way of doing!

What about something like this:

use strict; use warnings; my (@count, @patterns); push @patterns, qr /$_/ for qw/transaction find think save_param start +_sub url submit/; # you could also write a slightly more Perlish: my @patterns = ma +p { qr /$_/ } qw/transaction find think save_param start_sub url subm +it/; my $max = $#patterns; open my $FILEHANDLE, "<", "Action5.c" or die "cannot open < Action5.c: + $!"; while (<$FILEHANDLE>) { for my $i (0..$max) { $count[$i]++ if $_ ~~ $patterns[$i]; } } for my $i (0..$max) { print "Number of patterns found for $patterns[$i] is $count[$i] \ +n"; } close $FILEHANDLE;

This is untested, as you did not provide any data test file. A real data file might be useful also to clarify some of my questions below.

Note that I did not change the "if $_ ~~ $patterns..." part in the most inner loop because I don't know what you are exactly trying to achieve with the smart match operator, but I would be tempted to rewrite the line as:

$count[$i]++ if /$patterns[$i]/;

I also slightly changed your logic, because it seemed flawed to me: if your current data line matches, say, the first pattern, your program does not test the other patterns, whereas the same line could very well match two or more different patterns and should probably counted for the other patterns. If you really want to stop testing the patterns as soon as you've got one match, then you need to change my most inner loop to this:

$count[$i]++ and last if $_ ~~ $patterns[$i];

or

$count[$i]++ and last if /$patterns[$i]/;

I would advise to read very carefully each line of my suggested program, it is very very different from yours and you might learn a few things from it if you take the time to try to understand everything. And don't hesitate to ask if there is something you don't understand, my fellow brothers and myself will be happy to explain.


Comment on Re: Better way of doing!
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1049147]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (7)
As of 2014-04-23 23:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (557 votes), past polls