Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Determining if an element is already in an array.

by ithron (Acolyte)
on Feb 01, 2000 at 16:14 UTC ( #2654=perlquestion: print w/ replies, xml ) Need Help??
ithron has asked for the wisdom of the Perl Monks concerning the following question:

Besides some convoluted foreach loop, is there a way to determine if an element is already in an array before adding said element to the array?

Comment on Determining if an element is already in an array.
Re: Determining if an element is already in an array.
by dlc (Acolyte) on Feb 01, 2000 at 21:45 UTC

    the foreach loop is not so convoluted. i spell if f-o-r here.

    my @foo = qw(1 4 g 7 h rf s 4 6 7 9); my %foo = (); $foo{$_}=$foo[$_] for @foo; @foo=keys %foo;

    @foo is your original list, and %foo is a temporary hash that you will use to hold the unique values (since every key in a hash is unique).

Re: Determining if an element is already in an array.
by Anonymous Monk on Feb 02, 2000 at 00:04 UTC
    You can use the grep function: push(@foo,$elm) unless grep(/$elm/,@foo); Creating a hashtable every time you're tring to test for an element may be alot of overhead (memory and CPU).
RE: Determining if an element is already in an array.
by davorg (Chancellor) on Feb 02, 2000 at 01:17 UTC

    No need for a loop. Try this:

    my %check;
    
    @check{@arr) = (1) x @arr;

    You now have a hash %check which has a key/value pair for each element in the list. You can check for the existance of value, $val, by doing:

    if $check{$val}
Re: Determining if an element is already in an array.
by Anonymous Monk on Feb 02, 2000 at 18:23 UTC
    I'm sort of new to this, so maybe this is just 'baby talk', but this has always worked for me: push @arr, $el if !$seen{$el}++; The hash value $seen{$el} is not incremented until after the test and so is always zero the first time through, non-zero thereafter.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://2654]
help
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: (9)
As of 2014-12-25 10:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (160 votes), past polls