Capturing Output

Previous Table of Contents Next

Capturing Output

The system function does have a small shortcoming: It doesn't offer any particularly good way to capture the command's output and bring it into Perl for analysis. To do so in a roundabout way, you could use this workaround:

# 'ls' and 'dir' used for example only. opendir/readdir

# would be more efficient in most cases.

system("dir > outfile");    # Use "ls" instead of "dir" for Unix

open(OF, "outfile") || die "Cannot open output: $!";



In the preceding snippet, the command run by system has its output redirected to a file called outfile. The file is then opened and read into an array. The array @data now contains the output of the dir command.

This method is messy and not too clever. Not surprisingly, Perl has another way of dealing with this situation: backticks, also called backquotes. Any command that is surrounded by backticks (``) is run by Perl as an external commandas though through systemand the output is captured and returned as the return value from the backticks. Consider this example using backticks:

$directory=`dir`;    # Unix users, use ls instead of dir

In the preceding snippet, the dir command is run, and the output is captured in $directory.

Inside the backticks, all normal shell processing is observed: > does redirection, | does piping, and under Unix, & starts tasks in the background. Keep in mind, though, that commands that have been run in the background or that have had their output redirected with > have no output to capture.

In a scalar context, backticks return the output of the command as a single string. If the command output contains many lines of text, those lines all appear in the string, separated by record separator characters ("\n"). In a list context, the output is assigned to the list, with record separators at the end of each line.

Now consider this example:

@dir=`dir`;  # Use 'ls' for Unix users

foreach(@dir) {

    # Process each line individually.


In the preceding snippet, the output in @dir is processed in the foreach loop, one line at a time.

Perl has another way of representing backticksthat is, to use the notation qx{}. The command you want to execute goes between the braces ({}), as in this example:

$perldoc=qx{perldoc perl};

By using the qx operator, you can avoid the trouble of having to put backslashes in front of backticks when they appear as part of the command, as shown here:

$complex=`sort \'grep -l 'conf' *\``;  # Somewhat messy

You can rewrite the preceding snippet as fo
Previous Table of Contents Next

© 2000- NIV