Rob Dixon wrote:
Ramprasad wrote:

suppose I have a hash like

     %users =(
          'cvs' => {
                       'uname' => 'cvs',
                       'uid' => 582,
                       'gid' => 500
                     },
            'radvd' => {
                         'uname' => 'radvd',
                         'uid' => 75,
                         'gid' => 75
                       },
            'goofy' => {
                         'uname' => 'goofy',
                         'uid' => 515,
                         'gid' => 515
                       },
                 );

Now I want to sort on either of the fields 'uname' 'uid' 'gid'
and  ascending or descending Then my sort function is pretty repitive
code. I have to check if the field is numeric or not and then if the
sorting is ascending or descending.

assume $hash = \%users;
......
 if($sortkey eq 'uname'){
if($direction eq 'a'){
   @allunames = sort{ $$hash{$a}{$sortkey} cmp $$hash{$b}{$sortkey} }
keys %hash;
} else {
   @allunames = sort{ $$hash{$b}{$sortkey} cmp $$hash{$a}{$sortkey} }
keys %hash;
}
    } else {
if($direction eq 'a'){
   @allunames = sort{ $$hash{$a}{$sortkey} <=> $$hash{$b}{$sortkey} }
keys %hash;
} else {
   @allunames = sort{ $$hash{$b}{$sortkey} <=> $$hash{$a}{$sortkey} }
keys %hash;
}
    }
..............

Can someone suggest a better way.


Hi Ram.

Will this do?

sort {
  my ($va, $vb) = map $$hash{$_}{$sortkey}, $direction eq 'a' ? ($a, $b) : ($b, $a);
  $sortkey eq 'uname' ? $va cmp $vb : $va <=> $vb;
} keys %$hash;

Cheers,

Rob


Gr8 Now the code looks more neat.
Thanks

Do you think doing an explicit
 'if($direction eq 'a') { ...} else { ...}
Will be less expensive

Because in that case the $direction is checked only once here It is checked in every loop. That means bigger the hash , heavier the code will become

Can I not dynamically create my sort function , without the ifs , to suit the parameters on the fly and then use the sort function on the entire hash

Well anyway my actual data is not very big.
If I have to compromise on some cpu-cycles versus the code-readability I will go for better code-readability.


Thanks
Ram






-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]



Reply via email to