# Best Way to Check Uniqueness in Array

Discussion in 'Perl Misc' started by Kasp, Nov 13, 2003.

1. ### KaspGuest

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.
--

Kasp, Nov 13, 2003

2. ### Jürgen ExnerGuest

Kasp wrote:
> 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.

This has been discussed a few times before, please see "perldoc -q

jue

Jürgen Exner, Nov 13, 2003

3. ### Andreas KahariGuest

In article <bp06v3\$1ii9gm\$-berlin.de>, Kasp wrote:
> 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;

--
Andreas Kähäri

Andreas Kahari, Nov 13, 2003
4. ### Anno SiegelGuest

Andreas Kahari <> wrote in comp.lang.perl.misc:
> In article <bp06v3\$1ii9gm\$-berlin.de>, Kasp wrote:
> > 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

Anno Siegel, Nov 13, 2003
5. ### KaspGuest

> This has been discussed a few times before, please see "perldoc -q

Sorry, didn't do my homework
--

Kasp, Nov 13, 2003
6. ### Andreas KahariGuest

In article <bp0886\$2sl\$-Berlin.DE>, Anno Siegel wrote:
> Andreas Kahari <> wrote in comp.lang.perl.misc:

[cut]
>> @hash{@array} = 1;

>
> Why assign 1 to the hash slice, that's neither here nor there. Either
> leave all values undefined:
>
> @hash{@array} = ();

Yes, that makes more sense.

--
Andreas Kähäri

Andreas Kahari, Nov 13, 2003