remove redundant elements in an array

Y

Yiping Zhan

Say, @a = qw(1 2 3 1 4 5);

What is a good way to get (1 2 3 4 5)?

Thanks,

-- Newbie
 
M

Matt Garrish

Yiping Zhan said:
Say, @a = qw(1 2 3 1 4 5);

What is a good way to get (1 2 3 4 5)?

Use a hash to remove the duplicates and then just sort the keys if you want
to put them back in a array:

my %unique = map { $_ => 1 } @a;

my @b = sort keys %unique;

Matt
 
A

Anno Siegel

Bob Walton said:
@b{@a}=1;@b=sort keys %b;

Assigning 1 to the hash slice is a little misleading, don't you think?
It assigns 1 to what happens to be first in @a, and undef to the rest.
The reader would have to wonder about the special treatment and find
out that it doesn't matter. "@b{ @a} = ()" is clearer.

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,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top