views:

727

answers:

4

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?

+11  A: 

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

#!/bin/env perl
use warnings;
use strict;
Telemachus
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.
"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
A: 

you are forgetting the /usr/ directory.

-John

John T
env can be in different locations. On my system it is in /bin/env with a soft link to /usr/bin/env. Since it works form the command line, I assume he has the correct path the the program.
gpojd
It would be more portable to use /usr/bin/env.
Brad Gilbert
+14  A: 

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)

Douglas Leeder
+1  A: 

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