abc
abc

Reputation: 113

Perl - How does sort happen?

I have just started learning Perl. I was trying out some functions in Perl and came across the sort function. It worked fine with a set of input, but for a different input there was a different and unexpected result.

#!/usr/bin/perl

use warnings;
use strict;

use List::MoreUtils qw/ uniq /;

my @faculty = sort(1231,444,444,444,1232);

my @unique = uniq @faculty;
foreach ( @unique ) {
    print $_, "\n";
}

my @array1 = sort(3,3331,32,3);
my @array = uniq @array1;

print "My array = @array\n";

This is a sample script I wrote. The output for this is:

1231 1231 444 My array is 3 32 3331.

Why is 444 not sorted?

Upvotes: 0

Views: 104

Answers (3)

Glenn
Glenn

Reputation: 1167

Sorting is done as string be default so "1" is before "4" in string space, so 1234 will be less then 444. If you had 1, 2, 4, 10; the sorted order would 1,10,2,4;

If you want to sort them numerically (as numbers), then you need to supply block or routine to do the sorting. For example, you can use <=> for numeric comparison in a block with sort.

 my @faculty = sort { $a <=> $b } (1231,444,444,444,1232);

which will output 444, 1231, 1232.

Upvotes: 1

Leo Galleguillos
Leo Galleguillos

Reputation: 2730

Perl's sort routine sorts in alphabetical order by default. Therefore 1231 comes before 444.

To sort in numerical order, use the sort routine with the numeric comparison operator:

my @faculty = sort { $a <=> $b } (1231, 444, 444, 444, 1232);

Upvotes: 2

sotcha
sotcha

Reputation: 923

It is sorted as a character not as a number.

Try

my @faculty = sort {$a<=>$b} (1231,444,444,444,1232);

The output is :

444 1231 1232

You can check : sort

Upvotes: 3

Related Questions