Consider:
use warnings;
my @a = (1, 11, 3, 5, 21, 9, 10);
my @b = sort @a;
print "@b";
Output: 1 10 11 21 3 5 9
Codepad link: http://codepad.org/Fvhcf3eP
I guess the sort function is not taking the array's elements as an integer. That is why the output is not:
1 3 5 9 10 11 21
Is it?
How can I get the above result as output?
The default implementation of Perl's sort
function is to sort values as strings. To perform numerical sorting:
my @a = sort {$a <=> $b} @b;
The linked page shows other examples of how to sort case-insensitively, in reverse order (descending), and so on.
You can create explicit subroutines to prevent duplication:
sub byord { $a <=> $b };
...
@a = sort byord @b;
This is functionally equivalent to the first example using an anonymous subroutine.
You are correct. So just tell Perl to treat it as an integer like below.
use warnings;
my @a = (1, 11, 3, 5, 21, 9, 10);
my @b = sort {$a <=> $b} @a;
print "@b";
perl foop.pl
1 3 5 9 10 11 21
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With