Search code examples
linuxperlcommand-lineshquote

Single quotes behavior in a Perl one-liner 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

Solution

  • 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')")