Using -e and -s switch in perl

perl

Solution

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.

Problem

I am starting to lern Perl. I tried ``` perl -e 'print "The value of \$x=$x\n";' ``` gives: ``` The value of $x= ``` whereas: ``` perl -s -x=10 -e 'print "The value of \$x=$x\n";' ``` gives ``` No Perl script found in input ``` I would like to use the `-s` switch together with `-e` switch.. Why is it not working?

Original source