4.1. The system() Command

The system() function executes a shell command, while maintaining the same standard input, standard output and environment of the invoking script. If called with one argument, it passes this argument as is to the shell, which in turn will process it for special characters. If passed an array, it will call the command in the first member with the rest of the array as command line arguments.

If you receive an arbitrary array and you fear it may contain only one argument, you can use the system { $cmd_line[0] } @cmd_line notation (similar to print()'s ).

On success, system() returns 0 (not a true value) and one should make sure to throw an exception upon failure while referencing the built-in error variable $?.

Here are some examples, that will only work on UNIX systems.

#!/usr/bin/env perl

use strict;
use warnings;

(system("ls -l /") == 0)
    or die "system 'ls -l /' failed - $?";

my @args = ("ls", "-l", "/");
(system(@args) == 0)
    or die "Could not ls -l / - $?";

(system("ls -l | grep ^d | wc -l") == 0)
    or die "Could not pipeline - $?";

Written by Shlomi Fish