#!/usr/bin/perl use strict; use warnings; my $condition; my %scores = (Jim => 98, Mike => 82, Bill => 91, Joe => 61, ); my $expr = $condition ? '$scores{$b} <=> $scores{$a}' : '$scores{$a} <=> $scores{$b}'; print join "\n", sort {eval $expr} keys %scores; #### #!/usr/bin/perl use strict; use warnings; my $condition; my %scores = (Jim => 98, Mike => 82, Bill => 91, Joe => 61, ); my $code_ref = sub { if ($condition) { $scores{$b} <=> $scores{$a}; } else { $scores{$a} <=> $scores{$b}; } }; print join "\n", sort $code_ref keys %scores;