Can I use perl's switches with /bin/env in the

2019-04-03 15:55发布

问题:

I want to run perl -w using env. That works fine on the command line:

$ /bin/env perl -we 'print "Hello, world!\n"'
Hello, world!

But it doesn't work on the shebang line in a script:

#!/bin/env perl -w
print "Hello, world!\n";

Here is the error:

/bin/env: perl -w: No such file or directory

Apparently env doesn't understand the -w flag that I'm passing to perl. What's wrong?

回答1:

The hash-bang isn't a normal shell command-line, the parsing and white-space handling is different - that's what you've hit. See:

  • http://www.in-ulm.de/~mascheck/various/shebang/
  • http://homepages.cwi.nl/~aeb/std/hashexclam-1.html#ss1.3
  • http://en.wikipedia.org/wiki/Shebang_(Unix)

Basically many/most unixes put all of the remaining text after the first space into a single argument.

So:

#!/bin/env perl -w

is the equivalent of:

/bin/env "perl -w"

so you need to handle any options to the perl interpreter in some other fashion. i.e.

use warnings;

(as @Telemachus)



回答2:

Instead of -w use the warnings pragma (for modern versions of Perl):

#!/bin/env perl
use warnings;
use strict;


回答3:

I thought it might be useful to bring up that "-w" is not the same as "use warnings". -w will apply to all packages that you use, "use warnings" will only apply lexically. You typically do not want to use or rely upon "-w"



回答4:

It's worth noting that Mac OS X interprets characters after the shebang as arguments, so on OS X, the following will work:

#!/usr/bin/env perl -wT
enter code here

However, since one of the points of using #!/usr/bin/env is to foster cross-platform compatibility, it's probably best not to use that syntax even if you're on a Mac mostly.



回答5:

You are forgetting the /usr directory.