Perl “exec”: How to execute system commands

Summary: How to use the Perl backtick operator to execute system commands.


One of the real strengths of the Perl programming language is the ease in which you can access (execute) the commands of the underlying operating system. As other programming languages point out, this can be considered a weakness, because it also makes your programs system-dependent, but in reality I've found this to be a problem only five or 10 percent of the time. 

With Perl, the backtick operator (see the examples below) is one of the ways in which you can access system commands. To use this feature in Perl you just put the command that you want to execute between the backticks -- that's it. This runs the command, then you can easily access the command output. 

Perl `exec` example

Let's look at a simple "Perl exec" example to get started. Suppose I'm on the Unix/Linux system and I want to see the directory listing of my home directory (which I know is /home/al). This is all I have to do to get the directory listing and store it as one long string in a scalar variable:

$directoryListing = `ls -al /home/al`;
print $directoryListing;

As you can see, using the backtick operator is very simple. You can use it to run (execute) all types of operating system commands, even on Windows platforms. For instance, here is a similar example that will run on a Windows system:

$directoryListing = `dir c:\\`;
print $directoryListing;

More Perl execute power -- using variables

To make our "Perl execute" example even more powerful, you can use Perl variables inside of the backtick operators. This is very helpful inside of actual programs. For instance, instead of hard-coding the name of my home directory into the command in the previous example, we can imagine that this is running inside of a more complicated program, and that a variable was used to store the name of users home directory.

Here's the same Perl exec example as above, with the inclusion of a variable to store the users home directory:

$home = '/home/al';


$directoryListing = `ls -al $home`;
print $directoryListing;

Using an array variable instead of a scalar

Here's another tip that really doesn't have anything to do with the Perl backtick operator, but can be very useful for this example. Instead of storing the output in a scalar variable, you can store each individual line of output in an array variable. Then, once you have the information stored in an array, you can more easily work with one line at a time inside of your program. 

Here's the same Perl exec example one more time, this time with the output of the directory listing being stored in an array (or list if you prefer), where each line is printed out one record at a time:

$home = '/home/al';


@listOfFiles = `dir $home`;
foreach $i (@listOfFiles)
  print "FILE: $i";

I hope you find these "Perl exec" examples useful. Feel free to leave any questions or comments below.