How do I find, count, and display unique elements of an array using Perl?
Posted
by Luke
on Stack Overflow
See other posts from Stack Overflow
or by Luke
Published on 2010-05-12T15:14:43Z
Indexed on
2010/05/12
15:24 UTC
Read the original article
Hit count: 349
I am a novice Perl programmer and would like some help. I have an array list that I am trying to split each element based on the pipe into two scalar elements. From there I would like to spike out only the lines that read ‘PJ RER Apts to Share’ as the first element. Then I want to print out the second element only once while counting each time the element appears. I wrote the piece of code below but can’t figure out where I am going wrong. It might be something small that I am just overlooking. Any help would be greatly appreciated.
## CODE ##
my @data = ('PJ RER Apts to Share|PROVIDENCE',
'PJ RER Apts to Share|JOHNSTON',
'PJ RER Apts to Share|JOHNSTON',
'PJ RER Apts to Share|JOHNSTON',
'PJ RER Condo|WEST WARWICK',
'PJ RER Condo|WARWICK');
foreach my $line (@data) {
$count = @data;
chomp($line);
@fields = split(/\|/,$line);
if (($fields[0] =~ /PJ RER Apts to Share/g)){
@array2 = $fields[1];
my %seen;
my @uniq = grep { ! $seen{$_}++ } @array2;
my $count2 = scalar(@uniq);
print "$array2[0] ($count2)","\n"
}
}
print "$count","\n";
## OUTPUT ##
PROVIDENCE (1)
JOHNSTON (1)
JOHNSTON (1)
JOHNSTON (1)
6
© Stack Overflow or respective owner