Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

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

( #2482=categorized question: print w/ replies, xml ) Need Help??
Contributed by juahonen on Jan 26, 2000 at 17:07 UTC
Q&A  > arrays


Answer: How to find out if X is an element in an array?
contributed by Anonymous Monk

Try this to search for the presence of an element in an array.

my $element = 'Whatever you are searching for' ; if (grep {$_ eq $element} @TheArray) { print "Element '$element' found!\n" ; }
Answer: How to find out if X is an element in an array?
contributed by Corion

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"; };
Answer: How to find out if X is an element in an array?
contributed by davido

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.

Answer: How to find out if X is an element in an array?
contributed by little_mistress

You could do it like this:

my $element = "catchme"; my @array = ( "catchme", "if", "you", "can" ); if ( @found = grep { $_ eq $element } @array ) { my $found = join ",", @found; print "Here's what we found: $found\n"; } else { print "Sorry, \"$element\" not found in \@array\n"; }
I know that's a little longer than other answers but, I think this gives a little more detail and is easier to see how it works.
Answer: How to find out if X is an element in an array?
contributed by Roger

$X = "x"; @array = qw / x y z 1 2 3 /; return exists {map { $_ => 1 } @array}->{$X};
The above code returns 1 if element found, undef if not found.
Answer: How to find out if X is an element in an array?
contributed by mascip

This blog post discusses the best answers to this question.

As a short summary, if you can install CPAN modules then the best solutions are:

if any(@ingredients) eq 'flour';
or
if @ingredients->contains('flour');
However, a more usual idiom is:
if any { $_ eq 'flour' } @ingredients
which i find less clear.

But please don't use the first() function! It doesn't express the intent of your code at all. Don't use the "Smart match" operator: it is broken. And don't use grep() nor the solution with a hash: they iterate through the whole list. While any() will stop as soon as it finds your value.
Check out the blog post for more details.

PS: i'm answering for people who will have the same question in the future.

Answer: How to find out if X is an element in an array?
contributed by guha

#!perl use strict; use warnings; use List::MoreUtils qw{ any }; my @array = qw{ A B C D E X }; if (any { $_ eq 'X'} @array) { print 'YES'; } else { print 'NO'; }
Answer: How to find out if X is an element in an array?
contributed by linuxkid

Try using the modern "smart match" operator:

if ( $tofind ~~ @in ) . . .
Answer: How to find out if X is an element in an array?
contributed by russmann

Here is a super-fast script i just wrote using this information. It's for finding email addresses (elements) in one file that aren't in another.

#!/usr/bin/perl # File definitions $file1 = "first_file.txt"; # File with emails that might be duplicated + on 2nd file $file2 = "second_file.txt"; # These emails have already been used. $file3 = "finalemails.txt"; # Final product - emails that havn't been +used yet. # Load arrays with file contents open(FILE, "<$file1") || die "Can't open $file1\n"; @updatelist = <FILE>; close(FILE); open(FILE, "<$file2") || die "Can't open $file2\n"; @storelist = <FILE>; close(FILE); # Set %elements hash to 1 for each address in store list. foreach (@storelist) { $elements{$_} = 1; }; # Loop to create the final array of emails foreach $update(@updatelist) { if (!find_in_store($update)) { push @finallist, $update; } } # Write final array to file open(FILE, ">$file3") || die "Can't open $file3\n"; print FILE @finallist; close(FILE); # Routine to check for existance of an address. sub find_in_store { $element = $_[0]; if (exists $elements{$element}) { return(1); } else { return (0); } }
Answer: How to find out if X is an element in an array?
contributed by aarons

succinctly:

print grep { $_ eq $value } @list_of_values ? "present\n" : "absent\n";
Answer: How to find out if X is an element in an array?
contributed by rajib

$X = "x"; @array = ("y", "z", "x"); $i = 0; while (($i <= $#array && ($array[$i] ne $X)) { ++$i; } if ($i <= $#array) { # searched it & eureka return 1; # for true; } return 0; # for false;

Please (register and) log in if you wish to add an answer



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?
    Username:
    Password:

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

    How do I use this? | Other CB clients
    Other Users?
    Others making s'mores by the fire in the courtyard of the Monastery: (5)
    As of 2014-10-31 05:42 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      For retirement, I am banking on:










      Results (214 votes), past polls