Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

The other answers are all cool for arrays, but maybe using an array is wrong in the first place. Perl has a data type specialized for fast lookups, the hash (denoted by a % in front of the variable name). A lookup of an element in a hash is very fast, while grep and the likes have to go through the whole array, which is slower.

There are some drawbacks to hashes as well, first, they require you to change your code and second and more importantly, a hash dosen't preserve the order of elements - you can't get the elements back from the hash in the order you put them into the hash.

If the above drawbacks are no problem with you, you might want to use the following code :

#!/usr/bin/perl -w use strict; my %elements; my $element = "foo"; # Fill up our hash a bit foreach ("bla", "blubb", "foo", "bah") { $elements{$_} = 1; }; # now check if $element is in our hash : print "Found '$element'\n" if (exists $elements{$element}); print "D'oh - '$element' not found\n" unless (exists $elements{$elem +ent}); # You can still get to all elements in %elements : foreach (keys %elements) { # but they are in some weird order ... print "$_\n"; };

In reply to Re: How to find out if X is an element in an array? by Corion
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: (6)
As of 2024-04-19 07:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found