http://www.perlmonks.org?node_id=1039048


in reply to Sorting array

# changed your array to an array of arrays: my @arr = ( [ 'ch1', 100 ], [ 'ch2', 20 ], [ 'ch1', 13 ], [ 'ch2', 45 +], [ 'ch1', 1 ] ); # sort by chromosome then by position: my @sorted = sort { $a->[0] cmp $b->[0] or $a->[1] <=> $b->[1] } @arr; use Data::Printer; p @sorted; __END__ [ [0] [ [0] "ch1", [1] 1 ], [1] [ [0] "ch1", [1] 13 ], [2] [ [0] "ch1", [1] 100 ], [3] [ [0] "ch2", [1] 20 ], [4] [ [0] "ch2", [1] 45 ] ]

Replies are listed 'Best First'.
Re^2: Sorting array
by NetWallah (Canon) on Jun 14, 2013 at 23:38 UTC
    That doesn't quite give the output the OP requested, and will fail for multi-digit "ch.." values.

    If the entries always start with "ch", this code should work:

    perl -e 'my @arr = ( [ ch1=> 100 ], [ ch2=> 20 ], [ ch11=> 13 ], [ ch2 +=> 45 ], [ ch1=> 1 ] ); @s= sort( { substr($arr[$a]->[0],2) <=> sub +str($arr[$b]->[0],2) or $arr[$a]->[1] <=> $arr[$b]->[1]} 0..$#arr);pr +int qq|@s\n|' #Output: #4 0 1 3 2
    Note - OP's data has been modified slightly - adding a 2-digit "ch" value ("ch11").

    Also - this is not the most efficient sort for this kind of data, but will work well for small to medium size data. More complex transforms are required for efficiency with large amounts of data (For some definition of 'large').

                 "The trouble with the Internet is that it's replacing masturbation as a leisure activity."
            -- Patrick Murray

      I thought about that; however, all current genome annotation (that I've seen) has 0-padded #s such that if there are > 9 chromosomes, the first 9 would be ch01, ch02, etc. In the 'real world', it is much more likely to have zero-padding than to have chromosomes names 'ch'. But I agree, better safe than sorry.

      I am getting some error..BTW I have created the above mentioned @arr using following command

      push(@arr,($l2[6],$l2[7]));

      But you you specified

      my @arr = ( [ ch1=> 100 ], [ ch2=> 20 ], [ ch11=> 13 ], [ ch2 => 45 ], + [ ch1=> 1 ] );

      please advise changes in my command to get a format like you specified. Thanks in advance..

        Try:
        push @arr, [ $l2[6], $l2[7] ];
        See " perldoc perllol" to understand how this works.

                     "The trouble with the Internet is that it's replacing masturbation as a leisure activity."
                -- Patrick Murray

        I figured it out.. I need to use [] instead of ()..

        Never mind..

      Thanks much..This is what I needed..