in reply to Missing $ on loop variable

I'am almost confident this is a bug. How about the less verbose edition of this, which i'd use if i was writing the above code, which follows. Does it work?
my @found; my $line = 'Alpha and some junk here'; my @keywords = qw(alpha beta gamma); foreach (@keywords) { $line =~ m/$_/i ? push @found, $_ : next } foreach (@found) { print }

Replies are listed 'Best First'.
Re^2: Missing $ on loop variable
by revdiablo (Prior) on Dec 02, 2005 at 21:21 UTC

    When I see a ternary used in that fashion, I can't help but imagine you're one step away from condensing that down to:

    $line=~/$_/i&&push(@found,$_)for@keywords;

    Myself, I'd expand it a bit:

    for (@keywords) { next unless $line =~ /$_/i; push @found, $_; }

    I think it's a bit clearer and more obvious what's going on. Nothing earth-shattering, but a lot of these kind of things can add up.

    Update: then again, I might even go sideways on it:

    my @found = grep { $line =~ /$_/i } @keywords;
      Me and the ternary operator have a special relationship actually, i suppose it shows. Now that i take a more calm look at it, i'll take it one step further. I think the most elegant of all would actually be:
      foreach (@keywords) { push @found, $_ if $line =~ m/$_/i; }

      next is not really useful, and dare i say obsolete, since there is no other code aside the regexp conditional in the foreach block. As for the grep rewrite, there is a gotcha, which might complicate things in certain situations. But i'll save it for another day since it isn't relevant to this thread. But if anyone is interested take a look here.

        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). :-)

Re^2: Missing $ on loop variable
by superfrink (Curate) on Dec 02, 2005 at 21:51 UTC
    That example does not produce an error.
    $ cat psychotic.pl my @found; my $line = 'Alpha and some junk here'; my @keywords = qw(alpha beta gamma); foreach (@keywords) { $line =~ m/$_/i ? push @found, $_ : next } foreach (@found) { print } $ perl psychotic.pl ; echo alpha