Grep aliases the current value of $_ to the original array element, and thus modifying it actually tampers our original data
That's true, and good to point out. But it's also good to point out that for does the same thing. And the solution with grep is the same -- copy the values before modifying them. Which, incidentally, is exactly what my example snippet does. It copies the values into a new array. If you plug my example in just as I wrote it, the problem goes away:
my $line = "Alpha and some beta junk here"; my @keywords = qw(alpha beta gamma); my @found = grep { $line =~ /$_/i } @keywords; foreach (@found) { $_ = rand; } print "@keywords\n"; __OUTPUT__ alpha beta gamma
So, while the gotcha didn't affect my example directly, I'm glad you brought it up. Anyone who wasn't aware of it will likely benefit from this discussion.
In reply to Re^6: Missing $ on loop variable
by revdiablo
in thread Missing $ on loop variable
by superfrink
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |