Process management

This section shows how to execute a Unix shell command from within a Perl program.

How it works

You already know how to open a filehandle to a file for reading.
Let's store into the variable $filename the name of some external file we want to read from.
#!/usr/local/bin/perl

my $filename = "/somepath/filename"; 

open (DATA, $filename);

while ($line = <DATA>) {
  print "got $line"; # ... do something with $line ...
}

close (DATA);
We know that this code will open the external file, create the filehandle, enter a loop for receiving each line from the text and allow us to do some processing, and then close the external file.

Starting an external program and processing its output can be done in the same way.
This time, let's store into the variable $cmd the name of the program we want to execute, and all the parameters it expects, as if we were typing them on a unix command line.

The name of the variable containing the UNIX contained,
together with the UNIX pipe symbol | is supplied as the second parameter to the open command.

Examples

Executing the ls command

#!/usr/local/bin/perl

my $cmd = "ls -l";

open (LIST_FILES, "$cmd |");

while ($line = <LIST_FILES>) {
   print $line;
}

close (LIST_FILES);

Executing the who command

#!/usr/local/bin/perl

my $cmd = "/usr/bin/who";

open (DATA,"$cmd |");

while (my $line = <DATA>) {
  print "got $line"; # ... do something with $line ...
}

close (DATA);

Executing the lynx command

You can use the Lynx text browser for opening Web pages from within a Perl program.

Read about the main Lynx commands.

A command to query the OMIM database for the keyword "apoptosis" will be:


$cmd = "lynx -dump \"http://www3.ncbi.nlm.nih.gov/htbin-post/Omim/getmim?search=apoptosis\"";
Here's an example of a full Perl program that uses the lynx command to retrieve information from the Web.
Table of Contents.