Troubleshooters.Com and Code Corner Present

Steve Litt's Perls of Wisdom:
Spawning Other Programs
in Perl
(With Snippets)

Copyright (C) 1998 by Steve Litt


Contents

Introduction

An essential part of every programming language is the ability to run (spawn) other programs, whether or not the other programs are written in the language. If an already written program can do 90% of what you want to do, why re-invent the wheel?

Standard Perl has two syntaxes for spawning other programs: the system() command, and the backtick ` operator. The difference is that the backtick operator puts stdout from the spawned program into a Perl variable (hopefully a list). The system() command returns the exit code of the spawned program. Below is an example of each:

Backtick: Getting Novell Map Information

The backtick operator simply places the command (which may include command line arguments, pipe symbols, etc) between backticks (key at upper left of main key bank in a standard keyboard. The lowercase version of the tilde key). Remember that a backtick preceeds the command, and immediately follows the command:

Let's say you want to get an unused drive letter, but you don't feel like getting into the bowels of the Novell API.

#** Create hash of all letters above E (which is probably local)
my(%letters) = ('F'=>'~','G'=>'~','H'=>'~','I'=>'~','J'=>'~','K'=>'~',
   'L'=>'~','M'=>'~','M'=>'~','O'=>'~','P'=>'~','Q'=>'~','R'=>'~','S'=>'~',
   'T'=>'~','U'=>'~','V'=>'~','W'=>'~','X'=>'~','Y'=>'~','Z'=>'~');
#** Spawn Novell map command, place stdout into @maplines
my(@maplines) = `map`;  #NOTE: Backtick, NOT single quote!
#** Loop through all lines looking for used drive letters.
#** Delete any used drive letters from the hash
my($mapline);
my($unused);
foreach $mapline (@maplines)
  {
  #** Any "Drive X :=", etc, is used
  if($mapline =~ /^Drive\s+([A-Z])/) {delete($letters{$1))}
  #** Any "SEARCH= X:\APPS\MYAPP", etc is used
  if($mapline =~ /^SEARCH=\s+([A-Z])/) {delete($letters{$1))}
  }
#** Sort remaining (unused)letters. The first is what you seek.
@drives = sort(keys(%letters));
my($UnusedDriveLetter) = $drives[0];

NOTE: Although not used in this example, it's perfectly permissible to put command line arguments after the executable in the backtick operator.

System()

Use this if you want to see the output of the spawned program, or if you want to access the spawned program's return code, or if you don't want to use up a variable or memory to hold the outpuut of the spawned program, use system().

system("pkzip myback.zip $treename");

Beyond the Scope

There are spawning topics beyond the scope of this document. For instance, the Win32 Perl module contains methods to spawn programs and immediately continue Perl processing (instead of halting until the spawned program terminates). A spawned UNIX command line can be made to pipe stderr to stdout.


 [ Troubleshooters.com | Code Corner | Email Steve Litt ]

Copyright (C)1998 by Steve Litt -- Legal