in reply to Store operation in a variable

One solution would be to use an eval. This is a little clever/possibly fragile for my taste, but quite literally does what you want:

#!/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;

A more natural choice would be to just use sort's natural ability to take a subroutine/code ref as an argument:

#!/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;

I've used a closure above - if you are not familiar with them, perhaps a read-through of perlfaq7's What's a closure? would be helpful.