Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Re: Better way of doing!

by Laurent_R (Canon)
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];


$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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1049147]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2018-01-22 00:57 GMT
Find Nodes?
    Voting Booth?
    How did you see in the new year?

    Results (230 votes). Check out past polls.