[Israel.pm] how to sorting the hash elements dynamically
Offer Kaye
offer.kaye at gmail.com
Wed Jul 19 14:34:51 EEST 2006
On 7/19/06, rami doqa wrote:
> Hello Perl group:
>
> I am interesting in how can I do a dynamic sorting for
> the hash elements. ex:
>
> # code example
> $result->[1] = {
> 'key_1' => [14,20,37,46,..];
> 'key_n' => [10,42,15,60,..];
> };
>
> # Sometimes I want to sort the inner hash in ASC and
> sometimes DESC way
> # SO I am trying to do the following but i know an
> error will occur..
>
> if (# something...)
> {
> $syntax = "{$result->[1]{$a}[3] <=>
> $result->[1]{$b}[3]}"; # ASC
> }
> else
> {
> $syntax = "{$result->[1]{$b}[3] <=>
> $result->[1]{$a}[3]}"; # DESC
> }
> foreach my $key(sort $syntax keys (%{$result->[1]}) )
> {
> #do the DESC or ASC iteration...
> }
>
> my regards = "many";
> print "Rami Dakka";
>
>
Just refactor the code - have the condition appear inside the sort sub:
my $condition = ... ;
$result->[1] = {
'key_1' => [14,20,37,46,..];
'key_n' => [10,42,15,60,..];
};
sub conditional_sort {
return ($condition) ?
$result->[1]{$a}[3] <=> $result->[1]{$b}[3] :
$result->[1]{$b}[3] <=> $result->[1]{$a}[3] ;
}
foreach my $key (sort conditional_sort keys %{$result->[1]} ) {
#do the DESC or ASC iteration...
}
Regards,
--
Offer Kaye
More information about the Perl
mailing list