in reply to Shortcutting grep in boolean context

Alternate idiom:

$_ == $wanted and say("match"), last for @ary

Replies are listed 'Best First'.
Re^2: Shortcutting grep in boolean context
by ikegami (Patriarch) on Jan 03, 2017 at 21:36 UTC

    `for @a` also avoids putting every element of the array on the stack like `map @a` and `grep @a` do.

Re^2: Shortcutting grep in boolean context
by perlancar (Hermit) on Jan 03, 2017 at 21:31 UTC

    Ah yes, this is a nice idiom, and to use it in an expression, one can use e.g. do:

    if (do { my $found; $_ == $wanted and $found = 1 and last for @ary; $found }) { say "match" }'

      To avoid a temporary variable:

      if( sub{ $_ == $wanted and return 1 for @ary; 0 }->() ) { say "match" +}
        The sub version has a higher overhead than the do version, but the speed won't matter unless we do hundreds of thousands of calls per second or more.