Short-circuited Perl grep


/ Published in: Perl
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. # Short-circuited grep in scalar context, which returns 1 if an element of the
  2. # passed list is evaluated to true by the anonymous subroutine, without
  3. # continuing after one has been found.
  4. # -> Anonymous test subroutine operating on $_
  5. # List to test
  6. # <- 1 if an element matched, 0 otherwise
  7. sub shortgrep(&@)
  8. {
  9. my $test= shift @_;
  10. for (@_) {
  11. return 1 if &$test;
  12. }
  13. return 0;
  14. }
  15.  
  16. # simple example usage, made possible by prototype:
  17. if( shortgrep { $_->{"entry"} eq "value" } @arrayofhashes ) {
  18. ...
  19. }
  20. # "sub" and parentheses are still needed in more complex expressions:
  21. if( shortgrep(sub { $_ == 4 }, @ary) && $othercondition ) {
  22. ...
  23. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.