in reply to Re^2: Notation of sort function
in thread Notation of sort function

This is a good example for redundancy. Why not like this:
my @sorted = sort{ { $apples{$SORTVAR}->{golden} ? $apples{$SORTVAR}->{weight} * 10 : $apples{$SORTVAR}->{weight} }, '<=>' } keys %apples;
Here I specify the calculation to be performed only once, and as a second parameter, I pass the operator.

Replies are listed 'Best First'.
Re^4: Notation of sort function
by tybalt89 (Monsignor) on Oct 27, 2023 at 18:56 UTC

    There is:

    use List::AllUtils qw( nsort_by ); my @sorted = nsort_by { $apples{$_}->{golden} ? $apples{$_}->{weight} * 10 : $apples{$_}->{weight} } keys %apples;

    There is also a string compare version.

Re^4: Notation of sort function
by kcott (Archbishop) on Oct 27, 2023 at 16:03 UTC

    The special variables $a and $b are also used to specify order. Here's a very simple example:

    $ perl -E ' my @x = (23, 12, 45); say "Unsorted:"; say for @x; say "Ascending:"; say for sort { $a <=> $b } @x; say "Descending:"; say for sort { $b <=> $a } @x; ' Unsorted: 23 12 45 Ascending: 12 23 45 Descending: 45 23 12

    How would you implement that in your hypothetical syntax?

    — Ken

Re^4: Notation of sort function
by ikegami (Patriarch) on Oct 27, 2023 at 19:11 UTC
    use Sort::Key qw( nkeysort ); my @sorted = nkeysort { $apples{ $_ }{ weight } * ( $apples{ $_ }{ golden } ? 10 : 1 ) } keys( %apples );