Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: testing more than one item for equality

by davido (Cardinal)
on Oct 18, 2006 at 15:52 UTC ( [id://579121]=note: print w/replies, xml ) Need Help??


in reply to testing more than one item for equality

I actually kind of like that grep solution because it allows you to implement both "this or that", or "this and that". Here's how:

if( grep { $_ eq $test } ( $item1, $item2 ) ) { #..... This was an "or" } if( grep { $_ eq $test } ( $item1, $item2 ) == 2 ) { #..... This was an "and" }

This works because grep in scalar context returns the number of times it matched. If it matched an equal number of times to the number of elements being tested, all elements matched, so you've got a "this and that and that and that" condition.

This type of test is simplified even more (and definitely made easier to read) by using List::MoreUtils. That module offers an any and an all function:

use List::MoreUtils qw/ any all /; #Here is an "or" condition. if( any { $_ == 1 } ( 1, 2, 3 ) ) { print "True.\n"; # This one is true because one of the elements matched. } #Here is an "and" condition. if( all { $_ == 1 } ( 1, 2, 3 ) ) { print "True.\n"; # This one is NOT true, because only one of the three elements mat +ched. }

The List::MoreUtils solution is sort of like the grep solution, but IMHO, easier to "at a glance" understand what's going on, and thus a better choice for its clarity.

Quantum::Superpositions could be used like this:

use Quantum::Superpositions; if( any( 1, 2, 3 ) == 1 ) { print "True.\n"; } if( all( 1, 2, 3 ) == 1 ) { print "True.\n"; # This one fails because only one, not all elements matched. }

Though the Quantum::Superpositions solution looked the simplest, the module's own author (TheDamian) states that it is not intended for real world use. It was written more as a proof of concept, so while it's fun to play with, you probably shouldn't put it in production code. My own experience is that it's stable, but often slow, probably because it's such a brute force generalized approach to problems that may have more efficient specific solutions.


Dave

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (2)
As of 2024-04-20 03:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found