Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Sort on Table headers

by scorpio17 (Abbot)
on Apr 18, 2012 at 21:39 UTC ( #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
Node Status?
node history
Node Type: note [id://965809]
help
Chatterbox?
[shmem]: no. You're right.
[msh210]: About time... last time I was right was... I don't even remember when.
[shmem]: perl -e 'warn "test$/", ^@^ '
[Eily]: well, at least it's right about warn doing the same thing as die :)
[shmem]: same with undef as last element
[msh210]: oh, good point. It's the best kind of correct
[shmem]: msh210: but I'd not call it a lie outright. That's when you do know the truth.
[msh210]: I don't have sendmail (I'm on MS Windows), so does one of you think you can report the bug?
[shmem]: msh210: 'tis about time to tell the sad truth to perl5porters - via perlbug
[msh210]: probably whoever wrote that actually knows the truth

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (16)
As of 2017-04-24 12:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I'm a fool:











    Results (439 votes). Check out past polls.