Chankey Pathak
Chankey Pathak

Reputation: 21666

Sort function in Perl

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?

Upvotes: 4

Views: 6120

Answers (7)

Raoul
Raoul

Reputation: 3889

Guessing is the wrong approach. If you don't understand sort, look it up: sort

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

Upvotes: 3

mirod
mirod

Reputation: 16136

Use the spaceship operator: sort { $a <=> $b } @a

Upvotes: 4

Gidon Wise
Gidon Wise

Reputation: 1916

You are correct. So just tell Perl to treat it as an integer like below.

File foop.pl

use warnings;

my @a = (1, 11, 3, 5, 21, 9, 10);

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

print "@b";

Run

perl foop.pl
1 3 5 9 10 11 21

Upvotes: 7

Quick Joe Smith
Quick Joe Smith

Reputation: 8222

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.

Upvotes: 13

Rich Parker
Rich Parker

Reputation: 172

@b = sort { $a <=> $b } @a;

Is numerical

Upvotes: 4

mhyfritz
mhyfritz

Reputation: 8522

Provide a custom comparison function (comparing numerically):

sort {$a <=> $b} @array;

Upvotes: 6

RC.
RC.

Reputation: 28207

Here is a numerical sort:

@sorted = sort { $a <=> $b } @not_sorted   

Upvotes: 4

Related Questions