Perl - Removing duplicates from an array

XML, Perl, Python, and other languages can be discussed here, even if it isn't PHP (We might forgive you).

Moderator: General Moderators

Post Reply
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Perl - Removing duplicates from an array

Post by JayBird »

I have an array called final_array.

The elements of the array are read from a text file.

How can i iterate through the array to remove duplicates?


Cheerz

Mark
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post by JayBird »

if anyone is interested, thi is how you do it

Code: Select all

undef %saw;
   @final_array = grep(!$saw{$_}++, @final_array);
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

Code: Select all

my @arr = ('a', 'b', 'c', 'b', 'b', 'b', 'd', 'a', 'e'  );

# here's the trick
@arr = do { my %seen; grep !$seen{$_}++, @arr };


foreach my $element (@arr) {
	print $element, "\n";
}
it's not my idea, you will find it anywhere on the web ;)
User avatar
JAM
DevNet Resident
Posts: 2101
Joined: Fri Aug 08, 2003 6:53 pm
Location: Sweden
Contact:

Post by JAM »

if it weren't about perl
GAH! Edited because of stupidity.
Thanks volka. I was so thinking php here...
Last edited by JAM on Wed Aug 27, 2003 11:53 am, edited 1 time in total.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

nice idea...
if it weren't about perl ;)
Post Reply