Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Re^5: Smartmatch alternatives

by Laurent_R (Parson)
on Dec 17, 2013 at 18:52 UTC ( #1067507=note: print w/ replies, xml ) Need Help??

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

Comment on Re^5: Smartmatch alternatives
Select or Download Code
Re^6: Smartmatch alternatives
by LanX (Canon) 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, @_; }

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1067507]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (4)
As of 2014-10-01 01:31 GMT
Find Nodes?
    Voting Booth?

    How do you remember the number of days in each month?

    Results (386 votes), past polls