perl: force the use of command line flags?
I often write one-liners on the command line like so:
perl -Magic -wlnaF'\t' -i.orig -e 'abracadabra($_) for (@F)'
In order to scriptify this, I could pass the same flags to the shebang line:
#!/usr/bin/perl -Magic -wlnaF'\t' -i.orig
abracadabra($_) for (@F);
However, there's two problems with this. First, if someone invokes the script by passing it to perl directly (as 'perl script.pl', as opposed to './script.pl'), the flags are ignored. Also, I can't use "/usr/bin/env perl" for this because apparently I can't pass argume开发者_Go百科nts to perl when calling it with env, so I can't use a different perl installation.
Is there anyway to tell a script "Hey, always run as though you were invoked with -wlnaF'\t' -i.orig"?
You're incorrect about the perl script.pl
version; Perl specifically looks for and parses options out of a #!
line, even on non-Unix and if run as a script instead of directly.
The
#!
line is always examined for switches as the line is being parsed. Thus, if you're on a machine that allows only one argument with the#!
line, or worse, doesn't even recognize the#!
line, you still can get consistent switch behavior regardless of how Perl was invoked, even if-x
was used to find the beginning of the program.
(...)
Parsing of the
#!
switches starts whereverperl
is mentioned in the line. The sequences "-*" and "- " are specifically ignored so that you could, if you were so inclined, say#!/bin/sh #! -*-perl-*- eval 'exec perl -x -wS $0 ${1+"$@"}' if 0;
to let Perl see the -p switch.
Now, the above quote expects perl -x
, but it works just as well if you start the script with
#! /usr/bin/env perl -*-perl -p-*-
(with enough characters to get past the 32-character limit on systems with that limit; see perldoc perlrun
for details on that and the rest of what I quoted above).
I had the same problem with #!env perl -...
, and env
ended up being helpful:
$ env 'perl -w'
env: ‘perl -w’: No such file or directory
env: use -[v]S to pass options in shebang lines
So, just modify the shebang to #!/usr/bin/env -S perl -...
精彩评论