Click to See Complete Forum and Search --> : finding unique elements in an array.


buggy
09-27-2004, 04:16 AM
I have an unsorted array @elements, many of which are duplicates and I wish to print a list of unique elements (no duplicates). How could I go about doing this. I have takes scripts off the web but none of them work correctly.

Also the array will contain elements with errors, and I have been told that there may be a function in perl that removes elements that partially match.

eg DOE
Doeb

and DOE is only returned.

Charles
09-27-2004, 06:05 AM
#!c:/perl/bin/perl.exe -w

use strict;

my %foo;
$foo{$_} = 1 foreach qw (D o e b D o e b);
print sort grep {/[doe]/i} keys %foo;

buggy
09-27-2004, 06:43 AM
Sorry but this aint working for me. I have an array @elements which contains 10,000 elements. Can you see why, I am only new to the language.

Charles
09-27-2004, 07:34 AM
You havent given me much to work with - I have no idea what your filtering really looks lik - but extracting unique values is really easy. It's simply a matter of mapping the list to what is called a hash of booleans.

#!c:/perl/bin/perl.exe -w

use strict;

my @elements = qw(fee fie foe fum);

my %elements;
$elements{$_} = 1 foreach @elements;
print keys %elements;