Encapsulated cleverness

 | Perl | 5 Comments | 0 TrackBacks

Is there anyone out there who can tell me what the following piece of code actually does?

@list_out = keys %{ {map {$_=>1} @list_in} };

If so then please leave a comment if you dare. I am willing to bet a good many euros that not a single person out there knows the answer to this abstract perlishness.

Reference

No TrackBacks

TrackBack URL: http://www.kiffingish.com/cgi-bin/mt/mt-tb.cgi/31

5 Comments

This uniqifies a list, which can be determined by looking at the individual pieces from the inside out:

map {$_=>1} @list_in

map() processes each element in @list_in, and for each element it returns a list (, 1). When put in braces:

{ map {$_=>1} @list_in }

it yields a reference to an anonymous hash with the (key, value)
pairs coming out of the map. The trick here is that when a key
which already exists in the hash comes out of @list_in again, the
original is overwritten by the new value.

To dereference a reference to a datastructure, you put it in braces preceded by the sigil of the type of the datastructure ('@' for arrays, '%' for hashes, '$' for scalars, etc.). So this:

%{ { map {$_=>1} @list_in } }

yields a hash. We're only interested in the keys, which are the
values of the @list_in array, uniqified, so we use the keys() builtin on the hash to get a list of the keys:

@list_out = %{ { map {$_=>1} @list_in } };

And we're done. The problem with this approach is that the order of the elements is not preserved. Using List::MoreUtils::uniq() (which is 2 lines of code), does preserve the order.

In record time as usual Arjen, shouldn't have expected anything less (although obviously a cut-and-paste sleight of hand). I guess I owe you.

No cutting and pasting was involved, this is original content.

You're right, I was misled by your professional-looking content is all, and (unjustly) jumped to conclusions. Should have checked first. Keep up the good work.

You're right, I was mislead by the professional-looking content is all, and (unjustly) jumped to conclusions. Should have checked first. Keep up the good work.

Leave a comment

Recent Entries

A walk along the Keizersgracht
Too often one is so consumed by a jungle of intertwined thoughts that the beauty of the nearby surroundings ... »
Popularity is fickle
The popularity of a given next generation technology is very fickle, and its success or failure depends on many ... »
Where was Kiffin really buried?
Hi There seems to be some confusion on the current resting place of Kiffin Rockwell, some say that his ... »
Going to Portugal
Normally the week just before I leave for summer vacation, I spend hours on end desperately searching for some ... »
A human language
These days it is not very often that a new and exciting Perl book comes along. That's why I ... »