Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

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

by davido (Cardinal)
on Oct 01, 2003 at 07:56 UTC ( #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?

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (5)
As of 2023-03-27 01:30 GMT
Find Nodes?
    Voting Booth?
    Which type of climate do you prefer to live in?

    Results (63 votes). Check out past polls.