The problem with sort's default behaviour is that it sorts alphabetically. Here's snippet that incorrectly sorts numbers:
my @numbers = (20,1,10,2); my @incorrectly_sorted_numbers=sort @numbers; print "\n\nNumbers, incorrectly sorted\n"; print join "\n",@incorrectly_sorted_numbers;
Here's the output of this Perl script. Probably not what was intended.
1 10 2 20
If you want to have the numbers sorted by their value, you need use the <=> (aka Spaceship Operator):
my @numbers = (20,1,10,2); my @correctly_sorted_numbers = sort {$a <=> $b} @numbers; print "\n\nNumbers, correctly sorted\n"; print join "\n",@correctly_sorted_numbers;
The variables $a and $b are automatically set by Perl. The output is now:
1 2 10 20