Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Find duplicates in an array

2,357 views
Skip to first unread message

Gopal Karunakar

unread,
Jun 2, 2010, 3:37:06 AM6/2/10
to begi...@perl.org
Hi All,

I needed to find all the duplicate values in an array and their count of
occurences. Any help would be appreciated .


Thanks in advance.

Thomas Bätzler

unread,
Jun 2, 2010, 3:50:33 AM6/2/10
to Gopal Karunakar, begi...@perl.org
Gopal Karunakar <gk.kali...@gmail.com> asked:

> I needed to find all the duplicate values in an array and their count
> of occurences. Any help would be appreciated .

#!/usr/bin/perl -w

use strict;

my @array=qw(foo baz bar foo baz foo);

my %seen;

foreach my $item (@array){
$seen{$item}++
}

foreach my $item (keys %seen){
print "item $item seen $seen{$item} times.\n"
}

__END__

HTH,
Thomas

Taylor, Andrew (ASPIRE)

unread,
Jun 2, 2010, 4:03:49 AM6/2/10
to begi...@perl.org
>I needed to find all the duplicate values in an array and their count
of
>occurences. Any help would be appreciated .

You could use a hash:

use strict;
use warnings;

my @animals = ("cat","dog","wombat","cat","monkey","cat","monkey");
my %howmany;

foreach my $critter (@animals)
{
$howmany{$critter}++;
}

foreach my $key (keys %howmany)
{
print "$key $howmany{$key}\n";
}

If you only want cases with count > 1 then put an if around the print.


Capgemini is a trading name used by the Capgemini Group of companies which includes Capgemini UK plc, a company registered in England and Wales (number 943935) whose registered office is at No. 1 Forge End, Woking, Surrey, GU21 6DB.
This message contains information that may be privileged or confidential and is the property of the Capgemini Group. It is intended only for the person to whom it is addressed. If you are not the intended recipient, you are not authorized to read, print, retain, copy, disseminate, distribute, or use this message or any part thereof. If you receive this message in error, please notify the sender immediately and delete all copies of this message.

C.DeRykus

unread,
Jun 2, 2010, 7:11:05 AM6/2/10
to begi...@perl.org
On Jun 2, 12:37 am, gk.kalipuray...@gmail.com (Gopal Karunakar) wrote:
> Hi All,
>
> I needed to find all the duplicate values in an array and their count of
> occurences. Any help would be appreciated .
>

See: perldoc -q dup
perldoc perlvar

Although even non-dup array members get printed,
Data::Dumper and perl's pre-defined @ARGV can
be handy. Just pass the actual array members to
perl as command line arguments:


perl -MData::Dumper -e '$seen{$_}++ for @ARGV;
print Dumper \%seen'
foo bar bat foo

--
Charles DeRykus

0 new messages