Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: How to find out if X is an element in an array?

by davido (Cardinal)
on Oct 01, 2003 at 07:56 UTC ( [id://295548]=note: print w/replies, xml ) Need Help??


in reply to How to find out if X is an element in an array?

Yet Another Way....

You can use a temporary hash to build up the values contained in @array as hash keys. It then becomes trivial to check the existance of a key. You pay a price in speed and memory by copying the array to a hash, but you gain some speed and flexibility later on as you search for the existance of a particular item. Hash key lookups are, themselves, fast. That gain in speed and flexibility grows the more times you find yourself checking existances.

Here's the example code:

my @array = qw/This that the other and then some./; my %hash; @hash{@array}=(); my $look_for = "other"; print "'$look_for' exists\n" if exists $hash{$look_for};

If you're only looking for one thing, use one of the methods above. If you're looking again and again, this one is not too bad. You're not concerned that duplicate items within @array aren't preserved, because you're just using the hash to determine whether a particular item exists at least once. If you care about number of times, you can modify this approach so that the count is contained as the value matched to the key.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (3)
As of 2024-04-19 20:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found