Return to Snippet

Revision: 48824
at July 11, 2011 06:34 by deepsoul


Initial Code
# Short-circuited grep in scalar context, which returns 1 if an element of the
# passed list is evaluated to true by the anonymous subroutine, without
# continuing after one has been found.
# -> Anonymous test subroutine operating on $_
#    List to test
# <- 1 if an element matched, 0 otherwise
sub shortgrep(&@)
{
  my $test= shift @_;
  for (@_) {
    return 1 if &$test;
  }
  return 0;
}

# simple example usage, made possible by prototype:
if( shortgrep { $_->{"entry"} eq "value" } @arrayofhashes ) {
  ...
}
# "sub" and parentheses are still needed in more complex expressions:
if( shortgrep(sub { $_ == 4 }, @ary) && $othercondition ) {
  ...
}

Initial URL


Initial Description
To check the existence of an element in a Perl array with specific properties, one tends to use `grep`.  But this is inefficient because `grep` always checks each element. (Even in scalar context it returns the number of matching elements.)  The following function aborts after the first find.

Initial Title
Short-circuited Perl grep

Initial Tags


Initial Language
Perl