DEV Community

Dan
Dan

Posted on

The Perl Shebang

Often overlooked, the shebang of a Perl program is a comment on the first line which tells the (Unix-like) OS how to run the script when invoked directly on the commandline. (It's ignored on Windows, which only looks at the file extension.)

#!/usr/bin/perl
use v5.16.0;
use warnings;
say "Hello world";
Enter fullscreen mode Exit fullscreen mode
chmod a+x myscript.pl
./myscript.pl
Enter fullscreen mode Exit fullscreen mode

But there isn't one right answer for what the shebang should be. /usr/bin/perl may be commonly available, but not always, and may not be the perl the user prefers.

For Perl scripts that are distributed to users to run how they wish, use env to run the perl that comes first in PATH:

#!/usr/bin/env perl
Enter fullscreen mode Exit fullscreen mode

Perl scripts distributed on CPAN, however, get installed to a specific perl with their dependencies, so their shebang must also point to that perl. This is handled by a shebang rewrite step in the installation process, but it doesn't work for an env shebang for historical reasons.

For Perl scripts distributed via CPAN installation, you can use any single-word shebang that ends in perl, even just perl:

#!perl
Enter fullscreen mode Exit fullscreen mode

While developing and testing, the shebang will not have been rewritten yet, so you can invoke it as perl script/myscript.pl to run it with your preferred perl and ignore the shebang. If the script depends on modules in lib/ in the same distribution, it is common to run it during development as perl -Ilib script/myscript.pl.

Finally, when you deploy and install a script manually, it should be run with a specific perl so that it doesn't suddenly start running with a different perl from the one it was deployed for, which may not have the script's dependencies installed or may behave subtly differently.

For Perl scripts deployed to a specific location, use the full path to the perl that should run it on that machine:

#!/usr/bin/perl
#!/opt/perl/bin/perl
#!/home/user/perl5/perlbrew/perls/perl-5.34.0/bin/perl
#!/home/user/.plenv/versions/5.34.0/bin/perl
Enter fullscreen mode Exit fullscreen mode

You may also find Perl scripts with flags specified in the shebang with hyphens. This doesn't work with env shebangs in many cases, but the two common flags used this way are -w for warnings and -T for taint mode. -w is unnecessary and discouraged; just use warnings; instead.

Top comments (0)