sort an array unique.

R

rajendra

Hello All,
Is there any command to sort an array uniquelly,something similar to
"sort -u" in unix.

With Rgds,
Raj
 
P

Paul Lalli

Is there any command to sort an array uniquelly,something similar to
"sort -u" in unix.

Not built-in, but it's fairly easy to implement:

my %h = map { $_ => 1 } @unsorted_with_dups;
my @unsorted_uniques = keys %h;
my @sorted_uniques = sort @unsorted_uniques;

Or, you can remove all the intermediary steps:
my @sorted_unqiques = sort keys(%{{ map { $_ => 1 }
@unsorted_with_dups}});


Here's an example:
$ perl -le'
my @unsorted_with_dups = qw/d a e c b e d a c b e a b c e d/;
my @sorted_uniques = sort keys(%{{ map { $_ => 1 }
@unsorted_with_dups }});
print "@sorted_uniques\n";
'
a b c d e


Paul Lalli
 
P

Paul Lalli


Huh, so it is. For some reason, I'd forgotten about that. So my
short example gets even further reduced to:
$ perl -MList::MoreUtils=uniq -le'
my @unsorted_with_dups = qw/d a e c b e d a c b e a b c e d/;
my @sorted_uniques = sort(uniq(@unsorted_with_dups));
print "@sorted_uniques\n";
'
a b c d e

Thanks for the reminder,
Paul Lalli
 
R

Robert 'phaylon' Sedlacek

Paul said:
$ perl -MList::MoreUtils=uniq -le'
[...]
Thanks for the reminder,

No problem. I just learned how to import() via -M from you, so we're quid :)
 

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
474,202
Messages
2,571,057
Members
47,661
Latest member
sxarexu

Latest Threads

Top