Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: Compare all array values without a loop

by edan (Curate)
on Oct 19, 2004 at 14:19 UTC ( [id://400535]=note: print w/replies, xml ) Need Help??


in reply to Compare all array values without a loop

if ( grep { $_ eq $foobar} @array ) { }

Update: Use the above code if you really want to compare all array values (which is what you said). If you really want to just know if the value is in the array (and then stop searching), you might try the following, which might perform better in certain situations:

use List::Util qw(first); if ( first { $_ eq $foobar } @array ) { }
--
edan

Replies are listed 'Best First'.
Re^2: Compare all array values without a loop
by rjbs (Pilgrim) on Oct 19, 2004 at 14:25 UTC
    I believe the original poster wanted to know whether every value in the array equalled the given value, not whether it occurred once. Perhaps he could clarify. (Of course, now both answers are available in replies.)
    rjbs

      I think it's not very clear from the original post, but my assumption was that the poster was looking to solve the "is this value in this list" problem, so that's what I solved. I think this is a far more common problem than "is this list composed exclusively of this value"... don't you?

      --
      edan

Re^2: Compare all array values without a loop
by ihb (Deacon) on Oct 20, 2004 at 00:21 UTC

    Assuming that $foobar isn't undefined you should have a definedness check for the return value of first too. $foobar may be 0 or "".

    If undef is allowed as comparision value, use

    defined( defined $foobar ? first { $_ eq $foobar } @array : first { not defined $array[$_] } 0 .. $#array )
    instead.

    ihb

    See perltoc if you don't know which perldoc to read!
    Read argumentation in its context!

Re^2: Compare all array values without a loop
by welchavw (Pilgrim) on Oct 20, 2004 at 14:23 UTC
    Quantum::Superpositions has any() and all() operations that may fit the bill. I don't know how the performance compares to List::Util and don't have time to check. Its just a fun module.
Re^2: Compare all array values without a loop
by Anonymous Monk on Oct 19, 2004 at 14:22 UTC
    yay, thank you!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (7)
As of 2024-03-19 09:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found