in reply to Re: YARQ: multi_grep example in perlretut
in thread YARQ: multi_grep example in perlretut
Yes, it works this way, but you can improve it.
As a rule of thumb, use as small scopes as possible for variable declarartion, e.g. $pattern isn't used outside the foreach-loop (especially since $pattern is an alias to the current element of @compiled), and so it's useless to declare it "globally"
The same procedure with $line (although line is no alias, and the last content of line would stay in $line after the while block); if you write while( my $line = <> ) {, $line would only be usable within the while-loop-block, and you don't need to care if there is another $line somewhere outside the block which value is changed after the while loop)
use strict; use warnings; my $number = shift; # first usage my @regexp = (); # initialize before first usage, my $regexp[$_] wou +ldn't work $regexp[$_] = shift foreach (0..$number-1); my @compiled = map qr/$_/, @regexp; # first usage while( my $line = <> ) { # only in block foreach my $pattern (@compiled) { # only in block if( $line =~ /$pattern/ ) { print $line; last; } } }
or the like
And I guess you can write the shift foreach-line in a better readable way:
my $number = shift( @ARGV ); my @regexp = @ARGV[ 0..$number-1 ];
Best regards,
perl -e "s>>*F>e=>y)\*martinF)stronat)=>print,print v8.8.8.32.11.32"
|
|---|