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. ...

Get Learning Perl, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.