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

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)

Replies are listed 'Best First'.
Re^7: Smartmatch alternatives
by Laurent_R (Canon) on Dec 18, 2013 at 00:08 UTC
    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.
Re^7: Smartmatch alternatives
by Laurent_R (Canon) on Dec 18, 2013 at 15:55 UTC

    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, @_; }