Edit to include code from martin_100's question on sorting lines based on column 2 of a space-delimited file:

print map { $_->[1] } sort { $a->[0] <=> $b->[0] } map { [(split /\s+/)[1], $_] } read_file( $ARGV[0] );

Let's read the code in reverse order.

Read the file
read_file( $ARGV[0] );

Start by reading in the file line by line.

Convert each line into an anonymous array: [ 'column 2 text', 'full line of text']
map { [(split /\s+/)[1], $_] }

The lines are passed (as $_) to the 'first' map. $_ is implicitly passed to split /\s+/, which splits the line on spaces. (Note: the , $_ has nothing to do with the split!) Since it is wrapped in (...)[1], the split output is treated like a list in which the 2nd element is returned. This, itself, is inside [ ..., $_], which gives you an anonymous array containing the second element from the split ((split /\s+/)[1]) and the entire original line ($_).

Sort arrays based on first element of array (e.g., 'column 2 text')
sort { $a->[0] <=> $b->[0] }

These anonymous arrays are all passed along to the sort. Sort orders the arrays based on the first element of each anonymous array, hence the ->[0].

Pass second elements of sorted arrays (e.g., 'full line of text') to print statement
map { $_->[1] }

Now the sorted anonymous arrays containing both the second column of text and the entire line of text are passed to the 'second' map. This map passes only the second element of each array (the full original line) to the print statement, thereby printing the lines sorted based on the second column!


In reply to Re: how does these map statements work by frozenwithjoy
in thread how does these map statements work by martin_100

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.