my @array = qw/A B C B D B D/; my $c=1; foreach my $k (sort @array) { next if --$c; $c= scalar grep { $_ eq $k } @array; print "There are $c element(s) of $k\n"; }