Perl: Can someone please explain this code "sort { $a <=> $b } @unsorted"

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

I am having hard time understanding how this works? I know the output but interested to know the working.

Thanks in advance.

the spaceship operator, <=> , is a comparison function, for numeric data only. It compares elements in the input array, @unsorted . The output of the sort call is written to the array @sorted . If no comparison function statement was entered (a blank), then sort works on the @unsoted array as letters of the alphabet, not numbers.

$a and $b are individual elements in the unosrted array - in this case numbers

If element $a is equal to element $b , then it returns 0; if $a is less than $b it returns -1; if $a is greater it returns +1 .

So the general statement is:

@output_array = sort [optional comparison function]  @input_array

Internally perl sort calls a standard C library function, qsort for doing the comparisons and reordering over and entire array -or at least it did years ago.
qsort(3): sort array - Linux man page

3 Likes

Hi, Tanu.

If you were to execute perldoc -f sort , you would find explanation:

    sort SUBNAME LIST
    sort BLOCK LIST
    sort LIST
            In list context, this sorts the LIST and returns the sorted list
            value. In scalar context, the behaviour of "sort()" is undefined.

            If SUBNAME or BLOCK is omitted, "sort"s in standard string
            comparison order. If SUBNAME is specified, it gives the name of a
            subroutine that returns an integer less than, equal to, or greater
            than 0, depending on how the elements of the list are to be
            ordered. (The "<=>" and "cmp" operators are extremely useful in
            such routines.)
...

and if executed perldoc perldoc , one sees:

NAME
    perldoc - Look up Perl documentation in Pod format.

SYNOPSIS
        perldoc [-h] [-D] [-t] [-u] [-m] [-l] [-F]
...

so you can find answers to questions like this by yourself. Of course, not all documentation is easily understandable, so we can help in situations like that.

These commands were run on a system like:

OS, ker|rel, machine: Linux, 3.16.0-7-amd64, x86_64
Distribution        : Debian 8.11 (jessie) 
perl 5.20.2
Perldoc v3.23, under perl v5.020002 for linux

Best wishes ... cheers, drl

1 Like