Perl Sort Routine

A

Arthur

Hi All,

I pulled this sort routine off from one of the postings. It works
well, but I was hoping someone could actually explain to me exactly
what it is doing:

@in = qw(one two two four seven four five one six);
@out = sort grep(!$saw{$_}++, @in);
print "@out";

I'm lost with this line: @out = sort grep(!$saw{$_}++, @in);

What is !$saw($_)++ ???

Thanks,

Arthur
 
P

Paul Lalli

Hi All,

I pulled this sort routine off from one of the postings. It works
well, but I was hoping someone could actually explain to me exactly
what it is doing:

@in = qw(one two two four seven four five one six);
@out = sort grep(!$saw{$_}++, @in);
print "@out";

I'm lost with this line: @out = sort grep(!$saw{$_}++, @in);

What is !$saw($_)++ ???

Thanks,

Arthur

The line is sorting and returning elements of @in for which !$saw{$_}++ is
true. The grep goes through each element of @in, assigning each one to $_.
The first time each individual element is encountered, it is inserted as
the key to a hash %saw. It is inserted by taking advantage of
autovivification. That is, $saw{'one'}++ both creates the key 'one' in
the hash %saw, and immediately increments the value of that key. Since
'one' was previously not in the hash, the value was originally undef
(which gets treated as 0 by the ++ operator), and gets inremented to 1.
However, because the postfix form of ++ is being used, the expression
returns the value before incrementation - which is undef. The ! then
swaps that boolean, to make the entire !$saw{$_}++ expression return true.

The second and subsequent times the same value is seen, the position in
the hash already exists with a value of (at least) 1, and so the
expression returns a false value.

Therefore, the whole line is returning a sorted list of unique values from
the array @in.

Paul Lalli
 

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,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top