Using Backquotes to Capture Output

With system and exec, the output of the launched command ends up wherever Perl’s standard output is going. Sometimes, it’s interesting to capture that output as a string value to perform further processing. That’s done by creating a string using backquotes instead of single or double quotes:

    my $now = `date`;             # grab the output of date
    print "The time is now $now"; # newline already present

Normally, this date command spits out a string approximately 30 characters long to its standard output, giving the current date and time followed by a newline. When we’ve placed date between backquotes, Perl executes the date command, arranging to capture its standard output as a string value and, in this case, assigned to the $now variable.

This is similar to the Unix shell’s meaning for backquotes. However, the shell performs the additional job of ripping off the final end-of-line to make it easier to use the value as part of other things. Perl is honest; it gives the real output. To get the same result in Perl, add an additional chomp operation on the result:

    chomp(my $no_newline_now = `date`);
    print "A moment ago, it was $no_newline_now, I think.\n";

The value beween backquotes is like the single-argument form of system[321] and is interpreted as a double-quoted string, meaning that backslash-escapes and variables are expanded appropriately.[322] For example, to fetch the Perl documentation on a list of Perl functions, we might invoke the perldoc command repeatedly, ...

Get Learning Perl, Fourth 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.