anne has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to get unique elements in an array. The tricky part is I have a all_array that has values from 2 arrays a1 and a2. I push all the values into all_array. I have the dbids of records in Clearquest in the array. I get field value of the name using the dbids and then I have to find unique values of the names and push the corresponding dbids into an unique array. I have tried the following
$seen(); foreach $id (@all_array){ got the name using the id to $name push (@uniquearray, $id) unless $seen{name}++;}
But this does not seem to be doing what I need. Could any one suggest a way to accomplish this? Thanks

Replies are listed 'Best First'.
Re: Unique elements in an array
by jdporter (Paladin) on May 03, 2006 at 22:01 UTC

    FAQ. See How can I remove duplicate elements from a list or array?

    But maybe this will help:

    my %name_of_id; for my $id ( @all_ids ) { if ( ! exists $name_of_id{$id} ) { my $name = get_name_of_id($id); # whatever $name_of_id{$id} = $name; } }

    This could be more compactly written as

    $name_of_id{$_} ||= get_name_of_id($_) for @all_ids;
    but only if names are guaranteed to have non-false values.

    We're building the house of the future together.
Re: Unique elements in an array
by davidrw (Prior) on May 03, 2006 at 22:32 UTC
Re: Unique elements in an array
by GrandFather (Saint) on May 03, 2006 at 22:37 UTC

    In general in Perl when you think "unique", think also "hash". If you are dealing with unique entities then you should consider using a hash rather than an array. Often that seems silly bcause the inforamtion you are storing in the hash is really the key rather than the value. However the clean up in the code is very often worth the (memory) overhead of using a hash.

    In the case of your pseudo code it looks like a hash is a natural fit in any case. You seem to be mapping from an ID to a name - exactly what a hash's key => value mapping is all about.


    DWIM is Perl's answer to Gödel
Re: Unique elements in an array
by l.frankline (Hermit) on May 04, 2006 at 07:01 UTC

    Try this: List::MoreUtils

    uniq() function is available for your requirement. Hope it will be helpful to you.

    Don't put off till tomorrow, what you can do today.

      Thanks everyone. I will try it out.
Re: Unique elements in an array
by Praveen (Friar) on May 04, 2006 at 06:17 UTC
    Try This
    @list =(1,2,2,3,4,4,5); map{$hs{$_}++} @list; print keys %hs;