Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm looking for a way to implement the "any" and "all" tests for arrays. I've discovered the any() and all() subroutines published by Graham Barr in File::Utils. To recap:
# One argument is true sub any { $_ && return 1 for @_; 0 } # All arguments are true sub all { $_ || return 0 for @_; 1 }
But it isn't clear to me how to generalize this approach for more complicated expressions, such as "are all elements of my array equal to scalar 'foo'" and "is any element of my array equal to scalar 'bar'". I suppose I could say something like
# One argument is true sub any { $_ == 'bar' && return 1 for @_; 0 } # All arguments are true sub all { $_ == 'foo' || return 0 for @_; 1 }
But is that really the best I can do? I might like to have something like
if (all (@array == 'foo')) {
Or is that asking for too much?

Replies are listed 'Best First'.
Re: array comparison
by ikegami (Patriarch) on Dec 26, 2008 at 21:00 UTC

    These are already implemented in List::MoreUtils. The trick is the & prototype:

    sub any(&@) { my $cb = shift; $cb->() && return 1 for @_; 0 } sub all(&@) { my $cb = shift; $cb->() || return 0 for @_; 1 } if (all { $_ eq 'foo' } @array) { ... }

    By the way, == is the wrong operator to compare against 'foo'.
    == is the numerical comparison operator.
    eq is the string comparison operator.
    See perlop.

Re: array comparison
by FunkyMonk (Bishop) on Dec 27, 2008 at 00:21 UTC
    I've discovered the any() and all() subroutines published by Graham Barr in File::Utils
    Just in case any monks are looking for any and all, they're listed in List::Util as possible additions, not File::Utils (whatever that is). However, they're implemented (as ikegami said) in List::MoreUtils.
Re: array comparison
by jdporter (Paladin) on Dec 27, 2008 at 02:04 UTC

    Seems to me that what you'd really like is Quantum::Superpositions. It defines any and all, but differently than List::MoreUtils. Behold:

    use Quantum::Superpositions; my @a = ( 5 .. 8 ); print "Of @a:\n\n"; for ( 4, 6, 8 ) { print any(@a) > $_ ? "any > $_\n" : "not any > $_\n"; print all(@a) > $_ ? "all > $_\n" : "not all > $_\n"; }
    Between the mind which plans and the hands which build, there must be a mediator... and this mediator must be the heart.