why perl -e “print lc ”Hello-World/n“” prints 0

  • A+
Category:Languages

I have a code that I want to debug with perl's -e option from the command line. (from a Mac OS terminal, to be exact)

When I called a subroutine like that, I forgot to correctly match the double quote marks, kinda like that:

perl -e "print lc "Hello-World/n"" #Output: 0 

I was surprised to see 0 but, after looking closer, I saw that I had a problem with my double quote marks. Unsurprisingly, using outer single quote marks fixes the issue

perl -e 'print lc "Hello-World/n"' # Output(fixed): hello-world 

And now that I saw what the problem was, I am intrigued to see that it returned 0 in the first place. It looks like bash performed some kind of subtraction operation because if I repeat the same mistake by not having a dash there, I don't have that issue even with wrong double quote marks:

perl -e "print lc "HelloWorld/n""                   ^ closing the quotes too soon #Output: helloworldn 

So why is it that this syntax perl -e "print lc "Hello-World/n"" prints 0?

 


There's a useful trick to find out what perl is 'thinking'.

run perl -MO=Deparse -e "print lc "Hello-World/n""

perl -MO=Deparse -e "print lc "Hello-World/n"" print lc 'Hello' - 'Worldn'; -e syntax OK 

What's happening here is that perl is "seeing" Hello - Worldn as an arithmetic sum. And because the strings are numerically zero, you're printing 0-0. It's nothing to do with bash, but rather with perl and how it treats numeric values.

This is because barewords are acceptable if you're not using strict and warnings, but are coerced to numeric values by the subtraction (e.g. 0)

If you had turned on warnings:

perl -Mwarnings -e "print lc "Hello-World/n"" Argument "Worldn" isn't numeric in subtraction (-) at -e line 1. Argument "Hello" isn't numeric in subtraction (-) at -e line 1. 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: