Using -e and -s switch in perl

前端 未结 2 1669
北海茫月
北海茫月 2020-12-19 06:10

I am starting to lern Perl. I tried

perl -e \'print \"The value of \\$x=$x\\n\";\'

gives:

The value of $x=
<
相关标签:
2条回答
  • 2020-12-19 06:33
    perl -se 'print "The value of \$x=$x\n";' -- -x=10
    

    perlrun documentation could be more clear on this option,

    -s enables rudimentary switch parsing for switches on the command line after the program name but before any filename arguments (or before an argument of --). Any switch found there is removed from @ARGV and sets the corresponding variable in the Perl program. The following program prints "1" if the program is invoked with a -xyz switch, and "abc" if it is invoked with -xyz=abc.

    0 讨论(0)
  • 2020-12-19 06:39

    Arguments to the script itself should come after the script, regardless of whether it's a one-liner or a file. While not always necessary, you can separate the arguments for perl from the arguments to your script with a --:

    $ perl -s -E'say "\$x=$x"' -- -x=42
    x=42
    

    Ending the arguments to perl with -- is necessary because -x is a flag understood by perl itself, so your script would never see it. From perldoc perlrun:

    -x

    -xdirectory

    tells Perl that the program is embedded in a larger chunk of unrelated text, such as in a mail message. Leading garbage will be discarded until the first line that starts with "#!" and contains the string "perl". Any meaningful switches on that line will be applied.

    […]

    If a directory name is specified, Perl will switch to that directory before running the program. The -x switch controls only the disposal of leading garbage. The program must be terminated with "END" if there is trailing garbage to be ignored; the program can process any or all of the trailing garbage via the "DATA" filehandle if desired.

    The directory, if specified, must appear immediately following the -x with no intervening whitespace.

    As the specified input print "The value of \$x=$x\n"; does not contain a shebang, the actual script wasn't found and thus the error you encountered was emitted.

    Do not use -s switch parsing for any but the most simple one-liners. Use Getopt::Long instead.

    0 讨论(0)
提交回复
热议问题