Perl built-in routines and conditional operator for sorting

So, I have the following code that works:

my $cmp;                                                                    
if ( $action eq DEL ) {                                                     
    $cmp = \&cmpb;                                                          
}                                                                           
else {                                                                      
    $cmp = \&cmpf;                                                          
}                                                                           

foreach my $x ( sort $cmp keys %y ) {
    # do something
}

Both cmpb and cmpf are here:

sub cmpf { $a cmp $b }                                                          
sub cmpb { $b cmp $a } 

Now my question is: I would prefer something like:

foreach my $x ( sort $action eq DEL ? \&cmpb : \&cmpf keys %y ) {
    # do something
}

Or even better:

foreach my $x ( sort $action eq DEL ? { $a cmp $b } :  { $b cmp $a } keys %y ) {
    # do something
}

So, two questions. Firstly, what is the correct way to include these functions in a series, and secondly, why not work higher?

+4
source share
2 answers

Consider also

foreach my $x ($action eq DEL ? reverse sort keys %y : sort keys %y) {

which is pretty compact and pretty readable. Perl optimizes reverse sortby inverting all comparisons; it does not sort the list in one direction, and then cancels it.

+5
source

You can put a ternary operator inside a function sort.

foreach my $x ( sort {$action eq DEL ? $a cmp $b : $b cmp $a ;} keys %y ) {
    # do something
}

sort. { }.


@ysth ,

(, , , ) , Perl- . - ysth comment

foreach my $x ( $action eq DEL ? sort { $b cmp $a } keys %y : sort { $a cmp $b } keys %y )
+1

All Articles