Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: searching through array for multiple patterns

by si_lence (Deacon)
on Jul 16, 2009 at 07:56 UTC ( #780586=note: print w/ replies, xml ) Need Help??


in reply to searching through array for multiple patterns

I'm not sure I understand your question completely. If you want to print your 'found / not found' once, i.e. whether the pattern is present or absent in the array you could either join the array into a string an match the string (just make sure you don't create a match by joining the elements of the array) or have a flag that indicates a match and print your message after looping over your array.

use strict; use warnings; my @commands_run = qw(first second clock fourth); #join all elements of the array my $all_commands = join '#', @commands_run; if ($all_commands =~m/clock/) { print "\n Test -- found pattern -- \n"; } else { print "\n Test -- did not find pattern -- \n"; } #use a flag to indicate a match my $found = 0; foreach (@commands_run) { if($_ =~m/clock/) { $found++; } } $found ? print "\n Test -- found pattern -- \n" : print "\n Test -- did not find pattern -- \n";
cheers

si_lence


Comment on Re: searching through array for multiple patterns
Download Code
Re^2: searching through array for multiple patterns
by skirnir (Monk) on Jul 16, 2009 at 08:41 UTC
    in the latter case you don't need to continue the loop after you found a match. Thus I'd do it this way:
    #use a flag to indicate a match my $found = 0; foreach (@commands_run) { if($_ =~m/clock/) { $found++; last; # we have a match, exit loop } } $found ? print "\n Test -- found pattern -- \n" : print "\n Test -- did not find pattern -- \n";
    of course in this case you can omit the $found ? print ...: print ..; part:
    foreach (@commands_run) { if($_ =~m/clock/) { print "found pattern\n"; last; # we have a match, exit loop } }
Re^2: searching through array for multiple patterns
by si_lence (Deacon) on Jul 16, 2009 at 09:32 UTC
    You are perfectly right with your remarks about optimizing the loop.
    Good catch!

    cheers, si_lence

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (8)
As of 2014-10-21 02:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (95 votes), past polls