Learning Perl

Learning PerlSearch this book
Previous: 14.1 Using system and execChapter 14
Process Management
Next: 14.3 Using Processes as Filehandles
 

14.2 Using Backquotes

Another way to launch a process is to put a /bin/sh shell command line between backquotes. Like the shell, this fires off a command and waits for its completion, capturing the standard output as it goes along:

$now = "the time is now ".`date`; # gets text and date output

The value of $now winds up with the text the time is now along with the result of the date (1) command (including the trailing newline), so it looks something like this:

the time is now Fri Aug 13 23:59:59 PDT 1993

If the backquoted command is used in a list context rather than a scalar context, you get a list of strings, each one being a line (terminated in a newline[2]) from the command's output. For the date example, we'd have just one element because it generated only one line of text. The output of who looks like this:

merlyn     tty42    Dec  7 19:41
fred       tty1A    Aug 31 07:02
barney     tty1F    Sep  1 09:22

[2] Or whatever you've set $/ to.

Here's how to grab this output in a list context:

foreach $_ (`who`) { # once per text line from who
    ($who,$where,$when) = /(\S+)\s+(\S+)\s+(.*)/;
    print "$who on $where at $when\n";
}

Each pass through the loop works on a separate line of the output of who, because the backquoted command is evaluated within a list context.

The standard input and standard error of the command within backquotes are inherited from the Perl process.[3] This means that you normally get just the standard output of the commands within the backquotes as the value of the backquoted-string. One common thing to do is to merge the standard error into the standard output so that the backquoted command picks up both, using the 2>&1 construct of the shell:

[3] Actually, it's a bit more complicated that this. See the question in Section 8 of the Perl FAQ on "How can I capture STDERR from an external command?" If you're running Perl version 5.004, the FAQ is distributed as a normal manpage - perlfaq8 (1) in this case.

die "rm spoke!" if `rm fred 2>&1`;

Here, the Perl process is terminated if rm says anything, either to standard output or standard error, because the result will no longer be an empty string (an empty string would be false).


Previous: 14.1 Using system and execLearning PerlNext: 14.3 Using Processes as Filehandles
14.1 Using system and execBook Index14.3 Using Processes as Filehandles