Reputation: 767
I have a perl script, such as:
#!/usr/bin/perl -w use strict; my @vars = split(" ", "aaa bbb"); my @list = split(" ", "aaa"); foreach(@vars) { if ( grep(/$_/, @list)) { print "1\t"; }else{ print "0\t"; } }
I was hoping it gives "1 0" in return, but it is always "1 1". Does anyone know why ? I am using perl 5.8.8.
Thanks.
Chun
Upvotes: 1
Views: 403
Reputation: 118595
Because you are abusing the $_
variable.
Inside the expression of a grep EXPR, LIST
construction, $_
is aliased to an element of the list and the expression is evaluated. The previous value of $_
is not restored until the end of the grep
statement.
Since a naked /.../
expression is equivalent to $_ =~ /.../
, your grep
statement is just
grep $_ =~ /$_/, @list
with $_
aliased to an element of @list
, and which is true for most normal values of $_
.
The lesson is to not make $_
do too much work for you. Say
foreach $var (@vars) {
if ( grep(/$var/, @list)) {
print "1\t";
}else{
print "0\t";
}
}
instead. Anyone who looks at your code six months from now (including your future self) will thank you.
Upvotes: 7