in reply to sort direction
The problems with your mysort are that it is single purpose and it only sorts the %This_package::hash and nothing else. It is bad that one must read mysort to know that. The function is also poorly named and is defined at the wrong level. Defined in a logical, or problem domain modelling, sense.
If you can, use the standard style of sorting. This is to use the $a and $b variables to indicate how you are sorting. If you want a reversed sort you use $b $a to show that. This is to define the sort at a lower and more generic level.
I would suggest you use something like:
Then you can reverse the order of the arguments to num_or_str to reverse the sort. I consider that idiomatic Perl as below.sub num_or_str { no warnings 'numeric'; $_[0] <=> $_[1] || $_[0] cmp $_[1] } my @sorted = sort num_or_str( $people{$a}->{age}, $people{$b}->{age} ), keys %people;
If you really need a direction flag variable, you could keep it readable:
If you want to structure code more like your sample you should put the function around the sort. That is what I meant about creating the function at the wrong level.my @stuff = qw/ 9 -1 -3 hi 0 bye 5 10 /; my $descending = 1; my @ar; if ( $descending ) { @ar = sort { num_or_str($b, $a) } @stuff; } else { @ar = sort { num_or_str($a, $b) } @stuff; }
Then this higher level code is easier to understand:my $sort_by = 'age'; my $descending = 1; my $database = \%people; # return an ordered list of copies of keys of a # hash structured as described somewhere # usage: sort_people( \%sort_me, $by_me, $descending ) # Ascending sort is the default. # If $by_me is not a key that exists then ... # Maybe an arref should be returned. sub sort_people { my ( $people, $by, $desc) = @_; no warnings qw/ numeric uninitialized/; if ( $desc) { return sort { your_conditions( $b, $a)} keys %$people; } else { return sort { your_conditions( $a, $b)} keys %$people; } }
Be well,my @sorted_keys = sort_people( \%people, $sort_on, $descending);
|
|---|