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: $!";
@data=<OF>;
close(OF);

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 ...

Get Sams Teach Yourself Perl in 24 Hours 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.