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/bin/perl

$filename = "/some_directory/filename"; 

open (DATA, $filename)||die "Cannot open filehandle:$!\n";

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/bin/perl

$cmd = "ls -l";

open (LIST_FILES, "$cmd |");

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

close (LIST_FILES);

Executing the who command

#!/usr/bin/perl

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

open (DATA,"$cmd |");

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

close (DATA);

Executing the wget command

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

Read about the main wget commands.

A command to query the PDB database may look like:

$cmd = "wget \"
http://www.rcsb.org/pdb/download/downloadFile.do?fileFormat=pdb&compression=NO&structureId=1L4W\"";
 # 1L4W is the PDB accession number (PDB ID)
and a command to query the OMIM database for the keyword "apoptosis" will be:

$cmd = "wget \"http://www.ncbi.nlm.nih.gov/omim/?term=apoptosis\"";

Table of Contents.
Previous | Next