Monday 17 November 2014

Fetch Uniq elements from the array efficiently using grep or hash

Through hash:

my %faculty_hash = ();
foreach my $facs (@faculty) {
  $faculty_hash{$facs} = 1;
}
my @faculty_unique = keys(%faculty_hash);


Please note: Some of the answers containing a hash will change the ordering of the array. Hashes dont have any kind of order, so getting the keys or values will make a list with an undefined ordering.
To preserver the order of the elements use grep:


my %seen;
my @unique = grep { ! $seen{$_}++ } @faculty;

Other ways:
use List::MoreUtils qw/ uniq /;
my @unique = uniq @faculty;
foreach ( @unique ) {
    print $_, "\n";
}


Reference: 

http://stackoverflow.com/questions/439647/how-do-i-print-unique-elements-in-perl-array 

No comments:

Post a Comment

Tweets by @sriramperumalla