http://www.perlmonks.org?node_id=1067507


in reply to Re^4: Smartmatch alternatives
in thread Smartmatch alternatives

If you don't have any, it is easy to implement it using the reduce function of List::Utils with something like this:
sub any { my $code_ref = shift; reduce { $a or $code_ref->(local $_ = $b) } @_; }
Or, better:
sub any(&@) { my $code_ref = shift; reduce { $a or $code_ref->(local $_ = $b) } @_; }
which makes it possible to call it with a syntax similar to grep:
<strike>print "true\n" if any { $_> 11 } qw /3 12 4 5 7/; # prints tru +e
Update: the above line need to be this:
print "true\n" if any { $_> 11 } 0, qw /3 12 4 5 7/; # prints true

Replies are listed 'Best First'.
Re^6: Smartmatch alternatives
by LanX (Saint) on Dec 17, 2013 at 22:37 UTC
    your any is always true!

    DB<12> use List::Util qw/reduce/ DB<13> sub any(&@) { my $code_ref = shift; reduce { $a or $code_ref->(local $_ = $b) } @_; } DB<15> print "true\n" if any { $_ < 0 } qw /3 12 4 5 7/; true

    Cheers Rolf

    ( addicted to the Perl Programming Language)

      Oops, you are absolutely right. I must have changed something at the last moment, and don't remember exactly what. It was working OK, but not anymore. I am too tired now to figure out what happened, it will have to be tomorrow. I tested it with various arrays, it was working perfectly alright. But it's no longer the case.

      OK, to work correctly, the first element of the array passed to any needs to be false. There are two ways of doing it, I tested both ways, but then I made the mistake of removing both ways from my post. It can be done either as in the update I made in my post above (prepending a 0 to the list passed to any) or by changing the any function as follows:

      sub any (&@) { my $code_ref = shift; unshift @_, 0; reduce { $a or $code_ref->(local $_ = $b) } @_; }
      Thank you Rolf for your remark.

      Update: It could also be done this way, perhaps the best one:

      sub any (&@) { my $code_ref = shift; reduce { $a or $code_ref->(local $_ = $b) } 0, @_; }