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?
}{
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With