The sort function you have is not sorting by field at all. It is using the whole string. If you look at this line
map( [$_, (split('|', $_))[-1] ],
You'll see that it is constructing anonymous arrays where the first element in the array is the whole line ($_) and the second is the looks like it should be last pipe delimited field from that line (split('|', $_))[-1]. It isn't, but I'll get back to that.
However, if the sort block, it is using the first of these two elements $_->[0] which is the whole string.
For reasons I'll admit to not understanding split '|', 'abc|def|ghi' splits not on the pipe char, but every character? It therefore returns the list ('a', 'b', 'c', '|', 'e', 'f', '|', 'g', 'h', 'i')? This may be obvious to everyone else, but it fooled me.
The upshot of that is that when you changed the sort block to be sort( {$a->[1] cmp $b->[1] } what you where actually sorting on was the last character in the string which is the same for every line, hence the apparantly random sort order.
So, to correct that problem, I changed to split /\|/, $_. That means that the anonymous array passed to the sort will contain the string and the last field ([-1]), which isn't helpful if you want to sort by the first two. To address this we need to change that to a slice of the first two fields ([0,1]) and then modify the sort block to use these two fields. However as the second field is numeric, it makes the sort block a little more complicated. We need to compare the two first-fields first and if they are equal, then compare the two second-fields numerically. {$a->[1] cmp $b->[1] || $a->[2] <=> $b->[2]}.
Putting that all together and restructuring the code in the way I find most readable, I get:
$str =
join("\n",
map { $_->[0] }
sort{ $a->[1] cmp $b->[1] || $a->[2] <=> $b->[2] }
map { [$_, ( split /\|/, $_ )[0,1] ] }
split/\n/, $str
);
As none of the first fields in the sample data are the same, the second field is never compared, but if more or different data is used, the above would handle it.
Having worked through that, I get the sneaking suspicion that this is a very carefully constructed question of the homework variety?
Okay you lot, get your wings on the left, halos on the right. It's one size fits all, and "No!", you can't have a different color.
Pick up your cloud down the end and "Yes" if you get allocated a grey one they are a bit damp under foot, but someone has to get them.
Get used to the wings fast cos its an 8 hour day...unless the Govenor calls for a cyclone or hurricane, in which case 16 hour shifts are mandatory.
Just be grateful that you arrived just as the tornado season finished. Them buggers are real work. |