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


 
Thread Tools Search this Thread
Top Forums UNIX for Beginners Questions & Answers Perl: Can someone please explain this code "sort { $a <=> $b } @unsorted"
# 1  
Old 03-12-2019
Perl: Can someone please explain this code "sort { $a <=> $b } @unsorted"

Code:
@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.
# 2  
Old 03-12-2019
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:
Code:
@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
These 3 Users Gave Thanks to jim mcnamara For This Post:
# 3  
Old 03-14-2019
Hi, Tanu.

If you were to execute perldoc -f sort, you would find explanation:
Code:
    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:
Code:
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:
Code:
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
This User Gave Thanks to drl For This Post:
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Bash script - Print an ascii file using specific font "Latin Modern Mono 12" "regular" "9"

Hello. System : opensuse leap 42.3 I have a bash script that build a text file. I would like the last command doing : print_cmd -o page-left=43 -o page-right=22 -o page-top=28 -o page-bottom=43 -o font=LatinModernMono12:regular:9 some_file.txt where : print_cmd ::= some printing... (1 Reply)
Discussion started by: jcdole
1 Replies

2. UNIX for Beginners Questions & Answers

Extract delta records using with "comm" and "sort" commands combination

Hi All, I have 2 pipe delimited files viz., file_old and file_new. I'm trying to compare these 2 files, and extract all the different rows between them into a new_file. comm -3 < sort file_old < sort file_new > new_file I am getting the below error: -ksh: sort: cannot open But if I do... (7 Replies)
Discussion started by: njny
7 Replies

3. Shell Programming and Scripting

Is it Possible to sort a list of hexadecimal numbers using "sort" command?

Hello Everybody :) !!!. i have question in mind, is it possible to sort a list of hexadecimal numbers using "sort" command? (9 Replies)
Discussion started by: Kesavan
9 Replies

4. UNIX for Advanced & Expert Users

What does "__FD_PRN_" means in perl code ?

I have seen something like this in a perl code: $_ =~ s/__FD_PRN_/\\(/g What does this "__FD_PRN_" means. I have searched google but was not able to find any info regarding this. Appreciate if some one can refer to a link for these characters. From comments/code it used to substitue "(" with... (3 Replies)
Discussion started by: sarbjit
3 Replies

5. Shell Programming and Scripting

awk command to replace ";" with "|" and ""|" at diferent places in line of file

Hi, I have line in input file as below: 3G_CENTRAL;INDONESIA_(M)_TELKOMSEL;SPECIAL_WORLD_GRP_7_FA_2_TELKOMSEL My expected output for line in the file must be : "1-Radon1-cMOC_deg"|"LDIndex"|"3G_CENTRAL|INDONESIA_(M)_TELKOMSEL"|LAST|"SPECIAL_WORLD_GRP_7_FA_2_TELKOMSEL" Can someone... (7 Replies)
Discussion started by: shis100
7 Replies

6. Shell Programming and Scripting

Meaning of "b" modifier in "sort" command

I need to sort the following file by the rhdiskpower devices in the last column: Total_MB Free_MB OS_MB Name Failgroup Library Label UDID Product Redund Path 1024 851 1024 OCRVOT1_0000 OCRVOT1_0000 System UNKNOWN ... (3 Replies)
Discussion started by: wjssj
3 Replies

7. Shell Programming and Scripting

Is this "Out of Memory!" error due to sort() of perl how to resolve it?

I am running a program written in perl script and it is stopped with "Out of memory!" error. This is very strange because at the time then the program is aborted, it only used 4GB RAM and there are still 30GB free physical memory left in the system. I check the perl script and found the program... (3 Replies)
Discussion started by: lilili07
3 Replies

8. Shell Programming and Scripting

perl file, one line code include "length, rindex, substr", slow

Hi Everyone, # cat a.txt a;b;c;64O a;b;c;d;ee;f # cat a.pl #!/usr/bin/perl use strict; use warnings; my $tmp3 = ",,a,,b,,c,,d,,e,,f,,"; open(my $FA, "a.txt") or die "$!"; while(<$FA>) { chomp; my @tmp=split(/\;/, $_); if ( ($tmp =~ m/^(64O)/i) || ($tmp... (3 Replies)
Discussion started by: jimmy_y
3 Replies

9. Shell Programming and Scripting

Explain How ":=" works in shell scrpting

Hi , can any one explain how in the below code ":=" working in shell programming. L_DEBUG=${L_DBG:=N} if ; then set -x fi Thanks muddasas (2 Replies)
Discussion started by: muddasani
2 Replies

10. UNIX for Dummies Questions & Answers

Explain the line "mn_code=`env|grep "..mn"|awk -F"=" '{print $2}'`"

Hi Friends, Can any of you explain me about the below line of code? mn_code=`env|grep "..mn"|awk -F"=" '{print $2}'` Im not able to understand, what exactly it is doing :confused: Any help would be useful for me. Lokesha (4 Replies)
Discussion started by: Lokesha
4 Replies
Login or Register to Ask a Question