Hello perl guru,
I have a question on sorting. Browsing through the internet as well as here, I came across some code snippets on sorting. Finally, I did this (example from Tom C.) from his "FMTEYEWTK":
--
#!/usr/bin/perl
my $str = `type unsort.txt`;
$str = join("\n",
map($_->[0],
sort( {$a->[0] cmp $b->[0] }
map( [$_, (split('|', $_))[-1] ],
split(/\n/, $str)
)
)
)
);
print $str;
--
unsort.txt contains the following:
--
xyz4|1026|CR
xyz3|3461|CR
dert5|3251|PR
rtyaq|251|PR
dbca|583|PR
xxxt|360|CR
--
Output is the following which is correct:
dbca|583|PR
dert5|3251|PR
rtyaq|251|PR
xxxt|360|CR
xyz3|3461|CR
xyz4|1026|CR
But if I change the sort fn to
sort( {$a->[1] cmp $b->[1] }
which I am sorting the list using the first field as the key, then I got the following output:
--
xyz4|1026|CR
xyz3|3461|CR
dert5|3251|PR
rtyaq|251|PR
dbca|583|PR
xxxt|360|CR
--
1. The above is not sorted at all. What did I do wrong?
2. What if I want to sort using field 1 and field 2 as keys. What do I have to do? I have been trying to find answers from the WWW but to no avail.
I appreaciate your help. TIA.
Vincent
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.