Explain the deviousness of the Perl “preamble”

后端 未结 2 727
慢半拍i
慢半拍i 2020-12-03 11:12

The Perl manual describes a totally devious construct that will work under any of csh, sh, or Perl, such as the following:

eval \'(exit $?0)\' &         


        
2条回答
  •  时光说笑
    2020-12-03 11:56

    From Tom Christiansen's collection Far More Than Everything You've Ever Wanted to Know About …:

    Why we use eval 'exec perl $0 -S ${1+"$@"}'

    Newsgroups: comp.lang.tcl,comp.unix.shell
    From: bet@ritz.mordor.com (Bennett Todd)
    Subject: Re: "$@" versus ${1+"$@"}
    Followup-To: comp.unix.shell
    Date: Tue, 26 Sep 1995 14:35:45 GMT
    Message-ID:

    (This isn't really a TCL question; it's a Bourne Shell question; so I've cross-posted, and set followups, to comp.unix.shell).

    Once upon a time (or so the story goes) there was a Bourne Shell somewhere which offered two choices for interpolating the whole command-line. The simplest was $*, which just borfed in all the args, losing any quoting that had protected internal whitespace. It also offered "$@", to protect whitespace. Now the icko bit is how "$@" was implemented. In this early shell, the two-character sequence $@ would interpolate as

    $1" "$2" "$3" "$4" ... $n
    

    so that when you added the surrounding quotes, it finished quoting the whole schmeer. Cute, cute, too cute.... Now consider what the correct usage

    "$@"
    

    will expand to if there are no args:

    ""
    

    That's the empty string — a single argument of length zero. That's not the same as no args at all. So, someone came up with a clever application of another Bourne Shell feature, conditional interpolation. The idiom

    ${varname+value}
    

    expands to value if varname is set, and nothing otherwise. Thus the idiom under discussion

    ${1+"$@"}
    

    means exactly, precisely the same as a simple

    "$@"
    

    without that ancient, extremely weird bug.

    So now the question: what shells had that bug? Are there any shells shipped with any even vaguely recent OS that included it?

    -- 
    -Bennett
    bet@mordor.com
    http://www.mordor.com/bet/

提交回复
热议问题