Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this perl one liner in the bash works?

Tags:

linux

bash

perl

I was looking on how I could sort a file based on the length of each sentence and I came across this snippet from this answer

perl -ne 'push @a, $_ } { print sort { length $a <=> length $b } @a' input
                      ^ ^  

I tested it and it works but I don't have a clue how this works! As far as I can see the syntax is wrong. It has an open right bracket and a non closed right bracket which I have marked.
I am really having trouble figuring out how to run perl commands like this in bash
Could some one please explain this snippet?

like image 304
Jim Avatar asked Sep 15 '13 17:09

Jim


1 Answers

}{ is so called butterfly or Eskimo greeting Discovered by Abigail, in 1997.

Basically it closes while loop imposed by -n switch, and what follows }{ is block executed after while loop.

This is how perl parses this line,

perl -MO=Deparse -ne 'push @a, $_ } { print sort { length $a <=> length $b } @a' input

LINE: while (defined($_ = <ARGV>)) {
    push @a, $_;
}{ # <==here it is

    print((sort {length $a <=> length $b;} @a));
}

A more common way would be using END{} block instead of }{ operator:

perl -ne '
  push @a, $_ 
  END { 
    print sort { length $a <=> length $b } @a
  }
' input
like image 171
mpapec Avatar answered Nov 15 '22 06:11

mpapec