Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: Sort on Table headers

by scorpio17 (Canon)
on Apr 18, 2012 at 21:39 UTC ( [id://965809]=note: print w/replies, xml ) Need Help??


in reply to Sort on Table headers

I think you want something more like this:

use strict; use warnings; my @recordsArray; my @headers; while(my $line = <DATA>) { chomp $line; next unless $line; # skip blank lines if ($. == 1) { # first line? @headers = split(/\s+/, $line); next; } push @recordsArray, [ split(/\s+/, $line) ]; # store array ref } # sort first on column 2 (score), then on column 3 (value) # column 3 will only be used when column 2 values are the same my @sorted_array = sort { $a->[2] <=> $b->[2] || $a->[3] <=> $b->[3] } @recordsArray; print join("\t", @headers), "\n"; for my $row (@sorted_array) { # each element is an array ref... print join("\t", @$row), "\n"; # ...must dereference the array refs } __DATA__ ID distance score value start stop done remaining + N_425 614 17.01 425 40 12 308 322 N_542 1290 18.74 542 53 15 237 251 N_372 870 15.66 372 80 15 262 276 N_236 814 15.65 236 69 13 185 200 N_991 814 14.65 9 69 13 185 200 N_992 814 14.65 8 69 13 185 200 N_993 814 14.65 7 69 13 185 200 N_994 814 14.65 6 69 13 185 200 N_995 814 14.65 5 69 13 185 200

which produces this output:

ID distance score value start stop done remaining N_995 814 14.65 5 69 13 185 200 N_994 814 14.65 6 69 13 185 200 N_993 814 14.65 7 69 13 185 200 N_992 814 14.65 8 69 13 185 200 N_991 814 14.65 9 69 13 185 200 N_236 814 15.65 236 69 13 185 200 N_372 870 15.66 372 80 15 262 276 N_425 614 17.01 425 40 12 308 322 N_542 1290 18.74 542 53 15 237 251

I added some additional data, just to make sure it was sorting correctly when col 2 values for two rows were equal. If this isn't what you want, you'll have to clarify the problem.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://965809]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (2)
As of 2024-04-19 20:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found