How do I print unique elements in Perl array? How do I print unique elements in Perl array? arrays arrays

How do I print unique elements in Perl array?


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


Your best bet would be to use a (basically) built-in tool, like uniq (as described by innaM).

If you don't have the ability to use uniq and want to preserve order, you can use grep to simulate that.

my %seen;my @unique = grep { ! $seen{$_}++ } @faculty;# printing, etc.

This first gives you a hash where each key is each entry. Then, you iterate over each element, counting how many of them there are, and adding the first one. (Updated with comments by brian d foy)


I suggest pushing it into a hash.like this:

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