Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does perl oneliner output depend on switch positions

Tags:

perl

Can you please explain why perl switch -en does not work, but -ne works fine?

$ echo 123|perl -en 'print"$_"'
$ echo 123|perl -ne 'print "$_"'
123
$ 

Can you please give a link to documentation where such behaviour is described?

like image 861
bessarabov Avatar asked Oct 11 '13 11:10

bessarabov


3 Answers

After -e must follow perl code, but it follows only n which is not actual one liner, so -en can't work as you expect.

If you enable warnings with -w it will give you a hint:

echo 123|perl -wen 'print"$_"'

Unquoted string "n" may clash with future reserved word at -e line 1.
Useless use of a constant in void context at -e line 1.
like image 179
mpapec Avatar answered Nov 15 '22 00:11

mpapec


Every time the Perl interpreter see the -e option it expects one line of program to follow. This means that any other option for a particular line of code must come before the -e option otherwise the interpreter will get confused. In short it will treat any option after -e as command to execute. Keep in mind that you can use several -e in one line.

perl -e "print qq(Hello\n);" -e"print qq(World\n)"
                               ^  
                             Not space needed here.
#Output
Hello
World 
like image 31
edi_allen Avatar answered Nov 15 '22 00:11

edi_allen


Perlrun is the documentation you need.

There you can find the synopsis (in bold the aforementioned -n and -e):

perl [ -sTtuUWX ] [ -hv ] [ -V[:configvar] ] [ -cw ] [ -d[t][:debugger] ] [ -D[number/list] ] [ -pna ] [ -Fpattern ] [ -l[octal] ] [ -0[octal/hexadecimal] ] [ -Idir ] [ -m[-]module ] [ -M[-]'module...' ] [ -f ] [ -C [number/list] ] [ -S ] [ -x[dir] ] [ -i[extension] ] [ [-e|-E] 'command' ] [ -- ] [ programfile ] [ argument ]...

So as you can see from the above, the -e switch expects a 'command' immediately after being called, making the -ne 'command' valid and the -en 'command' invalid.

like image 35
psxls Avatar answered Nov 14 '22 23:11

psxls