7.1 Calling System Functions: system and backticks
We can call a system function by including the name of the system command to run as a string argument to the system command.
Program 7.1
#!/usr/bin/perl
#lssystem.pl
use strict;
my $result;
$result = system ("ls");
print "result = $result\n";
The call to system runs the Unix ls command. ls is a new process or program. The system command does not capture the STDOUT output of the new process or program that is run. For example,
system ("ls");
causes the ls command in Unix to run, but does not capture the listing of files that ls produces. When system is used to call a new program from within a program, the original program’s execution is suspended till the new program is finished running. In this case, although the ls command’s STDOUT output is not captured by Perl, the file listing shows up on the screen because ls produces the listing and directs it to STDOUT. The system command returns the so-called exit status of the new program. Usually a system program returns with an exit status of 0 if it succeeds and a non-zero value, say 1, if it does not. What is returned as failure exit status depends on the program. In this case, the listing caused by ls is printed on STDOUT
first, and then the exit code of 0 returned by ls is printed by the original program. The output of the program for one particular run is given below.
%lssystem.pl lsRFind1.pl lsbacktick1.pl lssystem.pl system.pl lsbacktick.pl lsbacktick1.pl~ lssystem.pl~ result = 0
It is possible to use the system call to run other Perl programs if the file name is given as the argument. For example, if in the current directory we have a Perl program called hello1.pl in addition to the program we want to run, we can run the program hello1.pl from inside the current program.
Program 7.2
#!/usr/bin/perl
#Running previously written scripts using "system"
print "Running the script hello1.pl\n";
system ("hello1.pl");
System commands can also be executed using the backtick method. The following program runs the system command ls using backticks.
Program 7.3
#!/usr/bin/perl #lsbacktick.pl use strict; my $listing; $listing = `ls`;
The program calls the system command ls to get a listing of files in the current directory. When a system command is run using backticks, the results returned by the command are returned by the backtick operator as a string. Thus, the variable $listing contains the string that would have been sent to STDOUT by ls. As a result, the ls command does not send its output to STDOUT in this case. This program prints nothing.
The following program prints the listing produced by ls.
Program 7.4
#!/usr/bin/perl #lsbacktick.pl use strict; my $listing; $listing = `ls`; print $listing, "\n";
The printing to STDOUT is not done by the ls command, but by the Perl script.