Contents Up Prev Next
Perl for Newbies - Lecture 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.

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
$dir =~ s!'!'\\''!g;

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

$count =~ /(\d+)/;
# Retrieve the number via the special regex variable $1
$count = $1;

print "There are $count directories\n";

Contents Up Prev Next

Written by Shlomi Fish