You unfortunately just stumbled into one of the genuine design-flaws of the Perl interpreter ...
The basic design flaw is lexicalizing (if that's even a word) the name of the $a special variable so that the homonym package variable becomes invisible (and also running without strictures or warnings).
c:\@Work\Perl\monks>perl -w -le
"my $a = 1;
;;
@unsorted = (2, 1, 4, 3, 0);
@sorted = sort { printf qq{$a<=>$b }; $a <=> $b } @unsorted;
print qq{\n};
print qq{@sorted};
"
1<=>1 1<=>3 1<=>4 1<=>1 1<=>0
0 2 1 4 3
I don’t recall if using a separate sort-comparison sub, rather than an inline anonymous, will address the matter or not. Can someone else please answer that?
I'm not sure why you can't answer the question yourself, but yes, a properly constructed named comparison function will sidestep the problem (update: although it would be better to address the issue directly):
c:\@Work\Perl\monks>perl -w -le
"my $a = 1;
;;
sub compare ($$) { my ($a, $b) = @_; return $a <=> $b; }
;;
@unsorted = (2, 1, 4, 3, 0);
@sorted = sort compare @unsorted;
print qq{@sorted};
"
0 1 2 3 4
Please see
sort.
Update: Changed code examples to eliminate keys %hash expressions of OPed code and use a plain array for unsorted elements.
Give a man a fish: <%-(-(-(-<