转自 perlfaq
#!/usr/bin/perl -w
# cnhackTNT { a t } perlchina.org
# Exacting Unique Elements from a
Array
# Just few tricks with perl's hash
&& grep
use strict;
my @array = ( 'This', 'is', 'a', 'array', 'with', 'a',
'duplicate','element' );
my $return1 = Unique_elem1(\@array);
my $return2 = Unique_elem2(\@array);
print join(',',@$return1),"\tby Unique_elem1\n";
print join(',',@$return2),"\tby Unique_elem2\n";
sub Unique_elem1(\@){
# eliminate duplicate values from a
array
# and don't care about the order of @array's
elements.
my $array=shift;
my %hash = ();
@hash{@array} = ();
$array=[keys %hash];
return $array;
}
sub Unique_elem2(\@){
# eliminate duplicate values from a
array
# and do care about the order of @array's
elements.
my $array=shift;
my %hash = ();
$array = [grep{!$hash{$_}++}@$array];
return $array;
}