in reply to Re^2: Too much SQL not enough perl
in thread Too much SQL not enough perl

Note that with a little skullduggery, you can make grep short-circuit. Granted, it's still much more clear to use List::Util 'first', and for searching the same candidate list many times, it's more efficient to use a hash.
my @candidates = qw(z y a b c a d a e a f); foreach my $question ('a', 'm') { if (do{{;grep {$_ eq $question ? do {print "Match\n"; last} : 0 } @candidates}}) { print "Found $question\n"; } }

Caution: Contents may have been coded under pressure.

Replies are listed 'Best First'.
Re^4: Too much SQL not enough perl
by Aristotle (Chancellor) on Oct 10, 2005 at 14:48 UTC

    Of course that really just uses grep for its side-effect, and you could just a little less twisted-brainedly say something like

    foreach my $question ('a', 'm') { if ( sub { $_ eq $question and return 1 for @candidates; 0; }->() +) { print "Found $question\n"; } }

    which is basically an inlined implementation of List::Util’s first.

    Makeshifts last the longest.

      Of course that really just uses grep for its side-effect
      No, it uses the return value as well. The interesting thing is that last is interpreted as true.

      Caution: Contents may have been coded under pressure.

        No, that’s not it. I admit I don’t (yet?) understand why that happens exactly, but what happens is that the last causes grep to return the entire list. Observe:

        my @candidates = qw( z y a b c a d a e a f ); foreach my $question ( 'a', 'd', 'm' ) { my @x = do { {; grep { $_ eq $question ? last : 0 } @candidates } +}; print "$question: @x\n"; } __END__ a: z y a b c a d a e a f d: z y a b c a d a e a f m:

        Update:

        <tye> grep works by moving things around on the stack and then reseting the count. you leave early, you get what's on the stack with the original count

        Makeshifts last the longest.