Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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.


In reply to Re: How to find out if X is an element in an array? by davido
in thread How to find out if X is an element in an array? by juahonen

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (3)
As of 2024-04-25 05:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found