Best Way to Check Uniqueness in Array

K

Kasp

Hello,

Consider an unsorted array
my @array = ( 2, 4, 6, 4, 2, 6, A, B, C, C, B, A);

Now, I wish to remove the duplicate elements from this array. A good way may
be to assign these array's elements as keys of a hash. And then convert the
keys back to the array like this:
<UNTEST CODE>

my @array = ( 2, 4, 6, 4, 2, 6, A, B, C, C, B, A);
my %hash = ();
for($i=0;$i<=$#array;$i++){
$hash{ $array[$i] } = '';
}

(@array) = (keys %hash); # @array now contains unique elements
</UNTEST CODE>

Is there a better or shorter way?

Thanks.
--
 
A

Andreas Kahari

Hello,

Consider an unsorted array
my @array = ( 2, 4, 6, 4, 2, 6, A, B, C, C, B, A);

Now, I wish to remove the duplicate elements from this array. A good way may
be to assign these array's elements as keys of a hash. And then convert the
keys back to the array like this:
<UNTEST CODE>
[cut]

my @array = qw( 2 4 6 4 2 6 A B C C B A );
my %hash;

@hash{@array} = 1;
@array = keys %hash;
 
A

Anno Siegel

Andreas Kahari said:
Hello,

Consider an unsorted array
my @array = ( 2, 4, 6, 4, 2, 6, A, B, C, C, B, A);

Now, I wish to remove the duplicate elements from this array. A good way may
be to assign these array's elements as keys of a hash. And then convert the
keys back to the array like this:
<UNTEST CODE>
[cut]

my @array = qw( 2 4 6 4 2 6 A B C C B A );
my %hash;

@hash{@array} = 1;

Why assign 1 to the hash slice, that's neither here nor there. Either
leave all values undefined:

@hash{@array} = ();

or set them all to 1:

@hash{@array} = (1) x @array;

or

%hash = map { ( $_, 1) } @array;
@array = keys %hash;

Mind you, your code works, but assigning 1 to one key and leaving the
others undefined makes no sense.

Anno
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top