Perl array sorting of numbers

Perl has in-built function called sort that can sort contents in array . By default sort  function consider the content as string. That means comparing the first character in both strings. “1” to “3”. “1” is ahead of “3” in the ASCII table and thus the string “12” will come before the string “3”.

my @numbers = (14, 3, 12, 2, 23);
my @sorted_numbers = sort @numbers;
say Dumper \@sorted_numbers;

Output :-

$VAR1 = [
    12,
    14,
    2,
    23,
    3
];

Perl don’t understand automatically that you need a sorting based on numerical methods.

No problem though as we can write a comparison function that will compare the two values as numbers. For that we use the <=> (also called spaceship operator) that will compare its two parameters as numbers and return 1, -1 or 0.

my @sorted_numbers = sort { $a <=> $b } @numbers;

Output:-

$VAR1 = [
    2,
    3,
    12,
    14,
    23
];