Search code examples
perlsorting

Perl - How do I sort an array of arrays based on the value of a column while maintaining the order specified in a hash?


%probes - is a list of probe names in an arbitrary order (organized by their location, not alpabetically nor numerically).

I need to sort an array of arrays (@data_a) based on the value of a the first column/cell in each array (the probe name) but sort them based on the order I specified in the ordered hash %probes.

@data_a looks like:

(
 (D88 5833.4 82544.0),
 (D92 3431.1 3432.1),
 ....
)


@data_asort=sort {$a->[0] cmp $b->[0]} @data_a;

Will sort by a specific column, and this works, but sorts alphanumerically:

(
 (100X 45454.1 48482.2),
 (105Y 49911.1 81819.2),
...
)

I see that:

@data_bsort=sort {$probes{$b} <=> $probes{$a}} keys %probes; 

Will sort a list of names based on the order in %probes.

I need to combine these two somehow, to sort the large array by the first column (probe name) maintaining all the numerical values associated, sorted in the order of %probes.

The order I want specified in the %probes hash:

my %probes = ("KCNT2 E3"=>1,"KCNT2 E1"=>2,"CFH E1"=>3,...);

The combined method suggested below:

@data_bsort= sort {$probes{$a->[0]} <=> $probes{$b->[0]} } @data_a;

Does not affect the order of the arrays, but this may be because it was meant to sort an array and not an array of arrays.


Solution

  • I believe based on what you wrote this is what you want:

    @data_sort = sort {$probes{$a->[0]} <=> $probes{$b->[0]} } @data_a
    

    That sorts the array refs in @data_a based on each array ref's first value being used as a key in the %probes hash.