Using Backquotes to Capture Output

With both 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. And that’s done simply 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, assign it to the $now variable.

This is very similar to the Unix shell’s meaning for backquotes. However, the shell also 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, we can simply 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 between backquotes is just like the single-argument form of system[*] and is interpreted as a double-quoted string, meaning that backslash-escapes and variables are expanded appropriately.[] For example, to fetch the Perl documentation on a list of Perl functions, ...

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