date command. Using the filehandle
method described above, we could do something like the following:
open(DATE,"date|");
$date = <DATE>;
chomp $date;
If there was a large amount of output to be read, and processing would
be done line by line, the pipe mechanism is probably the method of choice; but when
the desired output consists of only a few lines, perl offers a technique long used
in shell scripts. When you surround text with backquotes (`), that text
is interpreted as an operating system command, and the backquoted expression returns
the output of the command. In a scalar context, the entire output, possibly with
embedded newlines, is returned. In an array context, each line of output becomes
one element in the returned array.
The previous example could be written as
$date = `date`;
chomp $date;
or even further shortened to
chomp($date = `date`);
Keep in mind that when you use backquotes, you are running a separate
program under the operating system, not just invoking a function internal to perl.
In this particular example, the perl function localtime, used in a scalar
context will acheive the same result without running a separate program:
$date = localtime;
Efficiency issues like this should not unduly concern you. On the other
hand, if use of a feature like backquotes seems to be making your program run too
slowly, it is generally worthwhile to see if the functionality you're looking for
is built into the perl interpreter.
Variable interpolation takes place inside of backquotes, so there's a great deal
of flexibility in the way commands can be constructed. The following command
uses the diamond operator to list all the files in the current directory,
and then uses backquotes to read the output of the
UNIX file command to determine if the file is a JPEG or GIF image:
while(<*>){
if(`file $_` =~ /JPEG|GIF/){
print "$_ is an image file\n";
}
}
As an alternative to backquoting, the qx quoting operator
(Section 3.2) performs
a similar function.