How to call a subprocess in Perl

Subprocess calls with I/O response handling


In programming, subprocesses can execute shell commands and start applications by creating new processes. Subprocesses create a new process (as a child to the current process) programmatically from within your source code.

This tutorial explains how to call subprocesses in Perl by demonstrating a real-world example (unzipping an archive using unzip). It also covers how to handle I/O (not to be confused with Io) for subprocess outputs.

The exec() function

The exec function executes a system command and only returns (false) if the method doesn't exist or if directly called via the system shell.

Perl might also issue a warning if you have an exec function that isn't followed by a die / warn / exit statement. However, these warnings are only issued if you have them enabled.

exec("unzip -Z1 | grep -v '/$' >> log.txt");

The system() function

The system function does the same thing as exec. The only difference is that the system command creates a fork first, and the parent process waits for the child process to exit before continuing. In other words, the system function will terminate and return only after execution is complete.

system("unzip -Z1 | grep -v '/$' >> log.txt");

Capturing output

To capture the output, use backtick (`) strings to execute the command and store the response in a variable.

In the following example, we'll store the response of the previous command in a variable called $response:

$response = `unzip -Z1 | grep -v "/$"`;

Then print it to the terminal using the print keyword

print $response;