Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print unique elements in Perl array?

I'm pushing elements into an array during a while statement. Each element is a teacher's name. There ends up being duplicate teacher names in the array when the loop finishes. Sometimes they are not right next to each other in the array, sometimes they are.

How can I print only the unique values in that array after its finished getting values pushed into it? Without having to parse the entire array each time I want to print an element.

Heres the code after everything has been pushed into the array:

$faculty_len = @faculty;
$i=0;
while ($i != $faculty_len)
{
        printf $fh '"'.$faculty[$i].'"';
        $i++;
}   
like image 302
CheeseConQueso Avatar asked Sep 10 '25 02:09

CheeseConQueso


2 Answers

use List::MoreUtils qw/ uniq /;
my @unique = uniq @faculty;
foreach ( @unique ) {
    print $_, "\n";
}
like image 157
innaM Avatar answered Sep 12 '25 21:09

innaM


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)

like image 26
Robert P Avatar answered Sep 12 '25 23:09

Robert P