Run local Perl as root

This is a simple trick for conveniently running local Perl as a root user on UNIX-based systems.

Occasionally it's necessary to run locally-installed Perl as root. However at the command line if you type:

sudo perl program.pl

By default the Perl that is executed is the system Perl binary. This can be problematic as the System Perl may not have the modules required, or even be the correct version of Perl that you need to run. An easy fix for this is to use the which command:

sudo $(which perl) program.pl

By nesting which between a dollar sign parentheses, the terminal will resolve the command first, which returns a string to the local Perl binary. Sudo then operates on this binary instead of the system Perl binary. You can prove this with the following terminal commands:

which perl

sudo which perl

sudo echo $(which perl)

David is the founder and editor of PerlTricks.com. An organizer of NY.pm, he works as a technology consultant in New York City.