$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
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.
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.
@list =(1,2,2,3,4,4,5);
map{$hs{$_}++} @list;
print keys %hs;
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.
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