How do I print unique elements in Perl array?

Solution 1:

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

Solution 2:

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)

Solution 3:

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);