/ Published in: Perl
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.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
# 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(&@) { for (@_) { } } # 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 ) { ... }