I think the for someone who is not very familiar with map, the Schwartzian Transform is a complete mystery. It took me seeing map in action to appreciate its usefulness. So, in the interest of opening a novice's eyes...

The map function is one of Perl's more wonderous keywords. It's in my list of Perl Milestones of Enlightenment - mysterious at first, powerful yet simple in its action.

map takes two arguments: an operation of some sort (no pun intended) like a single keyword or a code block (as is used in this case). And a list to operate on. The example given in the pod offers:@chars = map(chr, @nums);. Which takes the list of @nums and performs the chr function on them and assigns the new array to @chars. Or, rewritten with a code block: @chars = map {chr}, @nums; Look right to left, bottom to top, to see the progression. On to the routine...

So what happens in Hofmator's implementation is every element in the list @unsorted goes through the code block of:

/^([+-])(\d+)h(\d+)m$/; [$_, sprintf("%s%d",$1,$2*60+$3)]

The regex splits up the string into +-, hours, and minutes, and the second half creates an anonymous array out of it: first element being the original string, $_, the second being the total minutes of the string.

Sort does its magic, sorting on the second element (that's 1). No calculation of minutes needed - already done by the map.

Then the map closest to the @sorted assignment takes the annonymous array, taking just the first element (the original string).

There's your sorted list of time strings with the minute calculation performed only once per array element.

HTH

-Ducky


In reply to Re: Re: Re: Sorting strings by ducky
in thread Sorting strings by rbi

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.