"Perl for Perl Newbies" - Part 4Executing Other ProcessesTrapping Command Output with `...`

4.2. Trapping Command Output with `...`

The backticks (or more generally qx{ ... }), can be used to trap the output of a shell command. It executes the command and returns all of its output. Interpolation is used.

If assigned to a scalar, it returns the output as a complete string. If the output is assigned to an array, the array will contain the lines of the output.

Here is an example for a program that counts the number of directories in a directory that is given as an argument:

#!/usr/bin/perl

use strict;
use warnings;

my $dir = shift;
# Prepare $dir for placement inside a '...' argument
# A safer way would be to use String::ShellQuote
$dir =~ s!'!'\\''!g;

my $count = `ls -l '$dir' | grep ^d | wc -l`;

if ($?)
{
    die "Error returned by ls -l command is $@.";
}

if ($count !~ /(\d+)/)
{
    # Retrieve the number via the special regex variable $1
    $count = $1;
    print "There are $count directories\n";
}
else
{
    die "Wrong output."
}

Written by Shlomi Fish