In the rightmost map,

map  { [$_, ($_ eq $first ? '' : $_)] } keys %$test;

The keys in %$test are converted to a list of arrays - [ key, key ], but with the `first' key having null for the second member of the array. (which will sort first with cmp).

Then, (s)he is then sorting by the second key, which will put the `first' key at the front:

sort { $a->[1] cmp $b->[1] }

If you want a string sort to ignore case, you should change this part to something like this:

sort { ( lc($a->[1]) cmp lc($b->[1]) ) or ( $a->[0] cmp $b->[0] ) }

So in general we compare the keys converted to lower case. Strictly speaking, this is all you need to do. The second comparison (which will only be tested if the first comparison returns 0, or equal) compares the raw keys directly. This is just to make the code a little more orderly, so you can expect it to return a consistent ordering of, eg `Case' and `case'.

So, to answer your question - the leftmost map statement is a no-op, however I suspect the coder may have intended to do this:

my @list = map { $_->[0] } ...

Then @list would be filled with the actual keys. Then it would be a correct Schwarzian transform.

Here is a much quicker and more efficient approach to sort a list and keep a key first:

my @list = sort { ( ($b eq $first) <=> ($a eq $first) ) or ( lc($a) cmp lc($b) ) or ( $a cmp $b ) } keys %$hash;

This gets rid of the need for all of those temporary anonymous arrays.


In reply to Re: Mapping, Sorting, Mapping on hash-keys by mugwumpjism
in thread Mapping, Sorting, Mapping on hash-keys by Tomte

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.