I don't think this has anything that isn't in one or other of the other posts, but avoiding two levels of dereference four times inside the sort block, should more than compensate for the simplicity of using reverse, to avoid having two of them.
I don't have much of a problem with your generic sort block. If the fields are consistantly numeric or non-numeric, it will do the right thing, and if they are not, it probably means that someone entered bad data and so long as the bad stuff is sorted to one end or the other it does much matter which.
The one time it could give you a surprise if your DOB contained stuff like "12th Jan 1901" and "12th december 2004", (ie. non-numeric strings that start with numbers), which would be grouped together by day, but otherwise be in a random ordering. Then again, sorting dates is pain unless they are in a fully numeric format (eg.YYYYMMDD) or similar. One thing that did strike me as odd was you maintaining both a DOB and AGE fields? If so, you create a consistancy problem with non-normailsed data.
#! perl -slw use strict; use Data::Dumper; sub rndStr{ join'', @_[ map{ rand $#_ } 1 .. shift ] } my %hash = map { $_ => { name => rndStr( 10, 'a'..'z' ), age => int 18+rand 80, sex => ( 'M', 'F', 'U' )[ rand 3 ], } } 1000001 .. 1000010; for my $orderBy ( qw[ name age sex ] ) { my $dir = ( qw[ ASC DESC ] )[ rand 2 ]; ## Just one, inline sort block with dereferencing only done once. my @sorted = sort{ local $^W; $a <=> $b || $a cmp $b } map{ $_->{$orderBy} } values %hash; ## Reverse if need be @sorted = reverse @sorted if $dir eq 'DESC'; ## And display print "\n$orderBy $dir"; print for @sorted } __END__ P:\test>498186 name ASC bbfxkykvpk bmhymyxlbm fcqxfmqtpc gbwvxqdecg glqaexowct ixptsmdruw kijumgktwv mpnnmcncjt porblnobmp uiwodoxvqo age DESC 90 76 76 58 48 47 45 35 26 22 sex DESC U U U U U U U M F F
In reply to Re: sort direction
by BrowserUk
in thread sort direction
by rsiedl
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |