Main Content

Run other processes from within your Perl program

Archive - Originally posted on "The Horse's Mouth" - 2012-12-03 15:40:54 - Graham Ellis

There are several ways in Perl that you can run another process from within your Perl program:

1. You can use a system call, which runs the other process independently and returns to you when it has completed. You can check the completion status of the system call by examining $?. Before it runs, system flushes all Perl files open for output before it runs the process. (from 5.6.0)

Example:
  system("ls");


2. You can run a command in backtics (or using qx). In this case, the command runs to completion and the results are then returned to you as a string.

Example:
  $results = `ls`;

3. You can open a command (process) on a file handle, using a pipe character | as the "direction" character. And you can then read from, or write to, that file handle to pick up results as the command runs.

Example:
  open (FH,"ls|");
  while (<FH>) {
    print ;
    }


In the first two cases, the command runs to completion before your Perl program carries on; in the third case, the command is running in parallel to your Perl program and you can read from before it is completed - that's very useful for handling something like a monitoring program which you want to interactively summarise / report on.

There are examples of all three syntaxes [here] - written as a demonstration during last week's Perl Programming Course.