in reply to flip-flop flop

Here's a technique you might find useful if you have Perl 5.10 or higher.

$ perl -Mstrict -Mwarnings -E ' > my @x = (0 .. 10); > my @y = grep { state $z = 0; $_ == 3 and $z = 1; $z } @x; > say qq{@y}; > ' 3 4 5 6 7 8 9 10

Update: I changed $_ > 3 to $_ == 3 to better illustrate the principle.

Sorry. Crap answer - see JavaFan's comments (below) for the reason why. Only read the first half of the question. Here's a better answer, in the same vein.

$ perl -Mstrict -Mwarnings -E ' > sub blah { my $z = 0; [ grep { /3/ and $z = 1; $z } @_ ] } > my @x = (0 .. 10); > say qq{@{blah(@x)}}; > my @y = qw{a b c 3 d e f}; > say qq{@{blah(@y)}}; > ' 3 4 5 6 7 8 9 10 3 d e f

-- Ken

Replies are listed 'Best First'.
Re^2: flip-flop flop
by JavaFan (Canon) on Mar 30, 2012 at 10:30 UTC
    Suffers from the same problem the OP describes. If you would use that grep a second time (because it's in a sub, or in a loop), the $z doesn't get reset -- that's what state is doing.

    Better (but untested):

    my @y = do {my $z = 0; grep {$z ||= $_ == 3} @x};
    Note that doesn't evaluate the condition ($_ == 3) after finding a match.

      ++ Thanks JavaFan, I've updated my post.

      -- Ken