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 -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]