ioana has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to understand how sort works so I took
the following file:
My|Text|5|ACGT
My|Text|2|ACGT
My|Text|4|ACGT
My|Text|3|ACGT
My|Text|1|ACGT
and I want to sort it using the thrid column (numbers)
as reference. Here is what I've tried to work with:
#!/usr/bin/perl my @rows = (); open FH, "LINE" or die $!; open FHO, ">SORT"; while (<FH>) { chomp; push @rows, [ split /\|/ ]; #I guess this should work with any separators,e.g \t as well? } close FH; #my @sorted = sort { $a->[2] <=> $b->[2] } @rows; #printf "%g\t%g\t%i\t%g\n", sort { $a->[2] <=> $b->[2] } @rows; #foreach ( sort {$a->[2] <=> $b->[2] } @rows ) { #printf "$_ \n" } print map {$_->[2] . "\n" } sort { $a->[2] <=> $b->[2]} @rows; #print map {$_ . "\n" } sort { $a->[2] <=> $b->[2]} @rows; exit
The print map command will only print out the sorted column
with numbers (and not the other columns). I've also tried to
print the data out using
for($i = 0; $i <4; $i++) { print map {$_->[$i] . "\n" } sort { $a->[2] <=> $b->[2]} @rows;
but it printed out the columns on top of each other. I would appreciate your help. I want especially to understand
how this works.
Thank you,
Ioana

Replies are listed 'Best First'.
Re: how to print sorted data
by Enlil (Parson) on Jul 15, 2003 at 20:46 UTC
    I am going to guess that you want to print the data back the way it was originally except that it is now sorted on the 3rd column. There are shorter ways to do this, but hopefully this is verbose enough to be helpful.
    use strict; use warnings; my @rows; while ( <DATA> ) { chomp; #split row and put in anon array pushed into @rows push @rows, [ split /\|/ ]; } #sort @rows (an Array of Arrays) by column; #@rows looks something like: (ARRAY(0x...),ARRAY(0x...),..) #where ARRAY(0x...) is just a reference to another array. my @sorted = sort { $a->[2] <=> $b->[2] } @rows; #since @sorted is now an array of Arrays sorted #we need to dereference what's in it to print it. foreach my $array_reference ( @sorted ){ #lets join the array pointed to in the array reference # with a "|" # @ dereferences the array #and print print join("|",@$array_reference),$/; } __DATA__ My|Text|5|ACGT My|Text|2|ACGT My|Text|4|ACGT My|Text|3|ACGT My|Text|1|ACGT

    As mentioned in the CB you might want to have a look at perlreftut, perldoc perllol, and perldoc perldsc for more on dereferencing (which you had to do to sort in the first place). (there is also references quick reference and intro to references on this site you can look at for more info). Hope this helps.

    -enlil

Re: how to print sorted data
by Zed_Lopez (Chaplain) on Jul 15, 2003 at 20:45 UTC
Re: how to print sorted data
by sgifford (Prior) on Jul 15, 2003 at 20:17 UTC
    <=> only sorts numbers; you want to use cmp to sort strings.