On 22/08/12 00:35, Uri Guttman wrote: > On 08/21/2012 05:33 PM, Eduardo wrote: >> On 21/08/12 22:05, Chris Stinemetz wrote: >>> Hello List, >>> >>> I am trying to sort a hash of arrays ( example below: ) >>> >>> I would the sort to sort in ascending order the first index of the >>> array >>> then the second index of the array. >>> >>> So in this example the arrays would sort to: >>> >>> 97,2,120,65 >>> 219,1,30,33 >>> 280,3,230,90 >>> 462,2,270,65 >>> >>> $VAR1 = { >>> '462-2' => [ >>> '462', >>> '2', >>> '270', >>> '65' >>> ], >>> '219-1' => [ >>> '219', >>> '1', >>> '30', >>> '33' >>> ], >>> '280-3' => [ >>> '280', >>> '3', >>> '230', >>> '90' >>> ], >>> '97-2' => [ >>> '97', >>> '2', >>> '120', >>> '65' >>> >>> }; >>> >>> Thanks in advance, >>> >>> Chris >>> >> Hi, test this: >> >> >> sub sorted >> { >> my ( $naa, $nab ) = $a =~ m|^(\d+)-(\d+)| && ( $1, $2 ); >> my ( $nba, $nbb ) = $b =~ m|^(\d+)-(\d+)| && ( $1, $2 ); >> return $naa <=> $nba unless $naa == $nba; >> return $nab <=> $nbb; > > since <=> will return 0 (false) if they are == you can just do this: > return $naa <=> $nba || $nab <=> $nbb; > yes, ofcourse, it's the same
> but that is a lot of coding to run for each sort comparison. check out > Sort::Maker for ways to do that with much less effort and faster as well. > > uri yes, ofcourse, (I repeat me), a lot of working, with a few register works well, but it's not the best. by hand, this is faster, maybe not the fastest, my %cache = (); foreach ( keys %$hash ) { my ( $naa, $nab ) = $_ =~ m|^(\d+)-(\d+)|; $cache{ ($naa * 100 + $nab ) } = $_; } foreach ( sort { $a <=> $b } keys %cache ) { print "[*] $cache{$_}\n"; } without repeating code, use a formula forcaching keys. you only need to know the size of the sendond keys. how would you do with Sort::Maker? thanks a lot, Uri Guttman Eduardo. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/