Reputation: 21
I'm new to perl and I tried to replace my foreach-statement (version 1):
use warnings;
use strict;
$cmd_list = "abc network xyz";
foreach my $item (split(" ", $cmd_list)) {
if( $item eq "network") {
$PRINT_IP = 1;
}
}
with a grep (version 2, from some example in the internet) which should give me the count (because of scalar context) of the value "network" in a string array:
$PRINT_IP = grep(/^$network$/, split(" ", $cmd_list));
for version 1 the if statement works as supposed, but for version 2 it always evaluates to false:
if($PRINT_IP) {
...
}
Where is my fault?
Upvotes: 0
Views: 454
Reputation: 66944
There seems to be a typo, as $network
is a variable; you may mean /^network$/
.
Having use strict;
in your program would have alerted you to an untended (so undeclared) variable. Having use warnings;
would have alerted you to the use of an uninitialized variable in regex compilation.
In the loop you only set the variable $PRINT_TP
(to 1) if there are any elements that match. Then List::Util has a function just for that
my $PRINT_IP = any { $_ eq 'network' } split ' ', $cmd_list;
or
my $PRINT_IP = any { /^network\z/ } split ' ', $cmd_list;
if you need regex for more complex conditions.
This returns 1
on the first match, the result that your for
loop produces. If you actually need a count then indeed use grep
. When there's no match $PRINT_IP
is set to ''
, an empty string.
The library is more efficient, firstly since it stops processing once a match happens. You can also do that by adding last
in your if
condition but List::Util
routines are generally more efficient.
More importantly: please always have use warnings;
and use strict;
at the beginning.
Upvotes: 5