Awesome, While I have been reading and writing perl for a few years now, I am always amazed at the code reduction that can occur when you properly apply the power of perl. This is the most instructive forum that I have ever joined. Thanks to you and all the others that post to this forum.
Chuck
[EMAIL PROTECTED] 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