Home: Perl Programming Help: Advanced:
How to remove duplicates from an array



DivyaG
Novice

Nov 5, 2009, 10:57 PM


Views: 6613
How to remove duplicates from an array

Hi,

Please help me out in removing duplicates from an array.
If possible, without using hashes.


Code
my @arr = (1,2,2,3,4,4,5); 
output should be @arr = (1,2,3,4,5);



shawnhcorey
Enthusiast


Nov 6, 2009, 3:29 AM


Views: 6604
Re: [DivyaG] How to remove duplicates from an array

perldoc -q duplicate

__END__

I love Perl; it's the only language where you can bless your thingy.

Perl documentation is available at perldoc.perl.org. The list of standard modules and pragmatics is available in perlmodlib.

Get Markup Help. Please note the markup tag of "code".


bichonfrise74
Novice

Nov 8, 2009, 1:48 PM


Views: 6538
Re: [DivyaG] How to remove duplicates from an array


Code
#!/usr/bin/perl 

use strict;

my @arr = (1,2,2,3,4,4,5);
my %seen;

map { $seen{$_}++ } @arr;
print sort keys %seen;



--bichonfrise74


DivyaG
Novice

Nov 8, 2009, 8:56 PM


Views: 6520
Re: [bichonfrise74] How to remove duplicates from an array

Thnx,
but is it possible to do the same task without using hashes?


bichonfrise74
Novice

Nov 8, 2009, 9:39 PM


Views: 6518
Re: [DivyaG] How to remove duplicates from an array

Oopps, I didn't see your original requirement. Anyway, see below.


Code
#!/usr/bin/perl 

use strict;

my @arr = (1,2,2,3,4,4,5);
my @uniq;

for my $i (@arr) {
push( @uniq, $i ) if ( ! grep { /\b$i\b/ } @uniq );
}

print join ',', sort @uniq;



--bichonfrise74


happypig
New User

Nov 18, 2009, 6:19 PM


Views: 6458
Re: [DivyaG] How to remove duplicates from an array

Golf Clubs | Titleist AP2 Irons| Taylormade R7 CGB MAX Irons |TaylorMade R9 Irons Ping G15 Irons || Callaway X-22 Irons


(This post was edited by happypig on Nov 18, 2009, 6:22 PM)


DeadByDawn
Novice

Jan 16, 2010, 1:00 PM


Views: 6005
Re: [DivyaG] How to remove duplicates from an array

the easiest way is to use 'uniq' sub from
List::MoreUtils

(standard perl module)


thillai_selvan
Novice

Mar 9, 2010, 1:06 AM


Views: 5441
Re: [DivyaG] How to remove duplicates from an array

If you want to use a module, try the uniq function from List::MoreUtils .
So there is no need of hashes.

Code
use strict; 
use warnings;


use List::MoreUtils qw(uniq);
my @unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 );
print "@unique\n";


This will output the following values

Code
1,2,3,4,5,6,7