19

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?

brian d foy
  • 129,424
  • 31
  • 207
  • 592
Frank
  • 64,140
  • 93
  • 237
  • 324
  • Also see how to do it with a little shell hackery [one](http://stackoverflow.com/a/9051635/128583) and [two](http://stackoverflow.com/a/3306658/128583). – Davorak Jan 07 '13 at 06:45

4 Answers4

26

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:

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)

Community
  • 1
  • 1
Douglas Leeder
  • 52,368
  • 9
  • 94
  • 137
16

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

#!/bin/env perl
use warnings;
use strict;
Telemachus
  • 19,459
  • 7
  • 57
  • 79
  • Yeah, I know about "use warnings", but I'm used to just write "perl -w" and I'm confused that "env" would work on the command line, but not in the script. – Frank Feb 20 '09 at 16:19
  • "perl -w" works on Unix, and is more concise, but it doesn't work on Windows (unless ActivePerl or what have you explicitly looks for command-line flags in a shebang line), so it's better to just "use warnings;". – Chris Lutz Feb 20 '09 at 17:39
6

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"

vhold
  • 61
  • 1
2

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.

Adam Ness
  • 6,224
  • 4
  • 27
  • 39