Made couple of changes. (One of those changes is to use '\|' instead of '|'):
my $str = `type unsort.txt`;
$str = join("\n",
map($_->[0],
sort( {$a->[1] <=> $b->[1] }#for alpha order change <=> to
+ cmp
map( [$_, (split('\|', $_))[1] ],#change this number to
+control which field to use, 0 for 1st field
split(/\n/, $str)
)
)
)
);
print $str;
Explaination:
- the split breaks the content of the file, into lines. Now we have a list contains all the lines;
- the inner map creates a list of array ref, which refs an array of two elements, the first one holds the entire line, when the second one contains the sorting key. You can choose which field to be used as the key;
- the sort sorts by the 2nd element, which is the key we choosen;
- the outter map then creates a list contains only the whole lines;
- finally, the join put the line breaks back, and form a string.