If you can guarantee uniqueness of the field you're sorting on, and if you're going to be manipulating these data by the field itself, sometimes it's useful to use the sorted column as the keys of a hash and drop the rest of the data into the hash as an associative array:
#!/usr/bin/perl
use warnings;
use strict;
package main;
my %data_set = ();
while(<DATA>) {
my @row = split/\s+/, $_;
$data_set{$row[3]} = [ $row[0], $row[1], $row[2] ];
}
foreach ( sort { $b <=> $a } keys %data_set ) {
printf "%-6d -> %-4d %-7s %-6d\n",
$_, $data_set{$_}->[0], $data_set{$_}->[1], $data_set{$_}->[2]
+;
}
__DATA__
0 TOTAL 11997 26981
0 root 1089 2594
1 daemon 0 0
594 pipmp01 591 1151
958 maestro 335 685
The output is:
C:\Code>perl hashsort.pl
26981 -> 0 TOTAL 11997
2594 -> 0 root 1089
1151 -> 594 pipmp01 591
685 -> 958 maestro 335
0 -> 1 daemon 0
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.