Perl System Command: An Easy Way to Access the OS System Command from Perl

perl operatorsPerl stands for Practical Extraction and Report Language. This language which was developed by Larry Wall, specifically designed for text processing. Programmers coming from a C or UNIX Shell background will find it easier to learn this popular and powerful programming language. Perl programs run on many different platforms such as Windows, Mac OS and the various UNIX operating system flavors.  This general purpose programming language is used for a wide spectrum of applications such as GUI’s, networking, web development and more. Perl is also open source and supports Unicode. One important feature of this language is it’s support for procedural and object oriented programming. The language is both stable and extensible. Perl is convenient to integrate with major databases such as Oracle, Sybase, MySQL and others.

In this tutorial, we walk you through details of the Perl System command and how to use it. This will require basic working knowledge of Perl, so if you’re new to Perl, you may want to first take this introductory Perl course.

Perl System () Function: What It Does

Perl’s system() function executes a system shell command. Here the parent process forks a child process, and then waits for the child process to terminate. The command will either succeed or fail returning a value for each situation.  The value 0 is returned if the command succeeds and the value 1 is returned if the command fails. Note that this is the reverse of conventional commands which return 1 on success and 0 on failure.

Learn more about system commands with this Linux course.

Perl has built-in commands to manipulate the file system and other parts of the operating system. If you know which platform you’re operating on, Perl system commands give you a way to execute shell commands on that platform. The syntax of system() function is as follows

system($command, @arguments);
  • The first parameter is the command to be executed.
  • The second parameter is the arguments to the command. There can be either a single argument or multiple arguments.

Let’s take an example:

system("ls -l");

This will output a long listing of files of the current working directory.

Points to Keep in Mind While Using Perl System Command

  • The return value of this function is the exit status of the program. The latter is returned by the wait function. In order to get the actual exit value divide the present value by the number 256.
  • If you want to know the errors passed to the operating system, by the external application you need to check $!.
  • To capture system’s output, enclose the command in backquotes. Take a look at some more examples.
@filelist= 'ls -l';

The above command will put the file into an array.

$myfilelist= 'ls -l';

The above command will put the files into a single string, demarcated by the newline character.

  • Perl system() function spawns a child process and goes to the sleep mode, while the command is being executed.
  • $^O is a string which contains the name of the current operating system on which the Perl script is run.  Take a look at the example given below.
if ($^O eq 'MSWin32') {
       system('dir');
     }
     else {
       syst0em('ls');
  }
}

Here the code checks whether the Perl script is on a Windows machine. If so, the window dir command is executed. Else we assume we are working on a Unix platform for which the Unix command ls is called by the system function.

  • Perl gets its environmental variables from the parent process. It is  possible to modify them before invoking the system function. Then each and every child process including the invoked system function can have access to the modified environment variables.

Example 1(a):How to call a vi editor using Perl system command in Unix

 #!/usr/bin/perl
    use strict;
    use warnings;
    my $status = system("vi employee.txt");

Here we call the vi editor of Unix from the command line. Note that you cannot capture the output of the program here.  The first line is the Perl interpreter binary and is also known as the shebang line. This is used on Unix like systems to locate the path of the path interpreter. The next two lines turn on the errors and warnings in Perl.

Learn how to write your own Perl programs with this course.

Example 1(b):To invoke the vi editor without involving the shell

#!/usr/bin/perl
    use strict;
    use warnings;
    my $status = system("vi", "employee.txt");

Here vi and the file are two separate arguments.

Example 2: Bit-shifting the return status

 #!/usr/bin/perl
    use strict;
    use warnings;
    my $status = system("vi", "employee.txt");
    if (($status >>=8) != 0) {
        die "Failed to run vi";
    }

In the above program, we bitshift the return value by 8. Alternatively you can divide the return value by 256 to get the actual return value of the called program. 

Example 3: Interpreting the system command’s failure

If you would like to find out the reason for system’s failure, you need to check and decipher the return value $?. This is done in the following program.

if ($? == -1) {
    print "command couldn't execute: $!\n";
    }
    elsif ($? & 127) {
    printf "The child process died with signal %d, %s coredump\n",
    ($? & 127), ($? & 128) ? 'with' : 'without';
    }
    else {
    printf " The child process exited with value %d\n", $? >> 8;
    }

If the value of $? is  -1 it means the command failed to execute. So we proceed to check the value of $! to interpret the failure. Perl has certain hard coded error values that represent different error conditions. Our program checks for these values and prints the corresponding message.

Alternatives to the Perl System Command

Other ways to execute external commands in Perl, in other scenarios  are as:

  • The exec() function can be used if one does not want to return to the calling perl script.
  • Backtick(‘ ‘) operator is useful when the output of the command needs to be captured.
  • Open() function is used in situations when the command is to be piped as input or output to the script.

Do try out the examples we’ve shown and feel free to experiment with them. Programming is best learned by practice. You may also want to check out this course on Bash Scripting and Python to see how it’s done in other scripting languages.