in reply to Re^3: Missing $ on loop variable
in thread Missing $ on loop variable

next is not really useful, and dare i say obsolete, since there is no other code aside the regexp conditional in the foreach block

I'd say I agree it's not useful in this code, but calling it obsolete doesn't make a whole lot of sense. You must be operating with a different definition of obsolescence than I am. ;-)

As for the grep rewrite, there is a gotcha, which might complicate things in certain situations. But i'll save it for another day

Please, by all means, don't save it for another day. Even for those of us who might already know of this "gotcha", mentioning it without even narrowing it down is not all that nice (and no, linking to the grep docs does not narrow it down). :-)

Replies are listed 'Best First'.
Re^5: Missing $ on loop variable
by psychotic (Beadle) on Dec 03, 2005 at 14:39 UTC
    As for the "obsolete" part, i used it --evidently badly-- as a synonym to "since there is no other code ... in the foreach block". Of course i was only refering to this snippet since next is invaluable in loop control. But i'm sure you knew that already. ;)

    As for the grep gotcha, here is the situation. Given this code:

    my $line = "Alpha and some beta junk here"; my @keywords = qw(alpha beta gamma); foreach (grep { $line =~ /$_/i } @keywords) { $_ = rand; } foreach (@keywords) { print "$_\n" }
    We get when run:
    0.623870849609375 0.16607666015625 gamma
    Grep aliases the current value of $_ to the original array element, and thus modifying it actually tampers our original data. It wasn't any special complication really, but has the potential to obfuscate a bug or two.
      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.