Wednesday, July 21, 2010

Extracting unique elements from a list...

@list = qw(a, b, c, d, a, e, b);

%seen = ( );
@uniq = ( );

foreach $item (@list) {
unless ( $seen{$item} ) {
#### we have not seen this item before
$seen{$item} = 1;
push(@uniq, $item);
}
}

##########faster method ####

foreach $item (@list) {
push (@uniq , $item) unless $seen{$item}++;
}

######simple method####
@uniq = sort -u @list;

No comments:

Post a Comment