Unique elements in an array
anne
created: 2006-05-03 17:54:37
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
Re: Unique elements in an array
created: 2006-05-03 18:01:24

FAQ. See [doc://perlfaq4#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
created: 2006-05-03 18:32:03
Also see node 280658
Re: Unique elements in an array
created: 2006-05-03 18:37:36

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
created: 2006-05-04 02:17:54
Try This
@list =(1,2,2,3,4,4,5);
map{$hs{$_}++} @list;
print keys %hs;
Re: Unique elements in an array
created: 2006-05-04 03:01:46

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.

Re^2: Unique elements in an array
created: 2006-05-04 10:55:16
Thanks everyone. I will try it out.

perlmonks.org content © perlmonks.org and anne, Anonymous Monk, davidrw, GrandFather, jdporter, l.frankline, Praveen

prlmnks.org © 2006 edmund von der burg (eccles & toad)

v 0.03