简体   繁体   中英

Single quotes behavior in a Perl oneliner on linux

Why does the second one-liner work despite the single quotes in it?

perl -wE 'say('Hello')'

# Name "main::Hello" used only once: possible typo at -e line 1.
# say() on unopened filehandle Hello at -e line 1.

perl -wE 'say length('Hello')'

# 5

In a shell command, 'abc'def , abc'def' , abcdef and 'abcdef' are all equivalent, so '...'Hello'...' is the same as '...Hello...' .


For perl -wE 'say('Hello')' , your shell calls

exec("perl", "-wE", "say(Hello)")

If the first argument of say is a bareword and no sub has been declared with that name, the bareword is used as a file handle.


For perl -wE 'say length('Hello')' , your shell calls

exec("perl", "-wE", "say length(Hello)")

If a bareword is found, no sub has been declared by that name, a file handle is not expected, the next token isn't => , and use strict 'subs'; is not in effect, the bareword is a string literal that returns itself.


Solutions:

perl -wE 'say("Hello")'           # exec("perl", "-wE", "say(\"Hello\")")

perl -wE 'say(q{Hello})'          # exec("perl", "-wE", "say(q{Hello})")

perl -wE 'say('\''Hello'\'')'     # exec("perl", "-wE", "say('Hello')")

Note that perl doesn't require the code to be a separate argument.

perl -wE'say("Hello")'            # exec("perl", "-wEsay(\"Hello\")")

perl -wE'say(q{Hello})'           # exec("perl", "-wEsay(q{Hello})")

perl -wE'say('\''Hello'\'')'      # exec("perl", "-wEsay('Hello')")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM