Wednesday, March 24, 2010

Executing and Capturing the output of a command on /bin/sh or cmd.exe using perl

qx/STRING/ or 'STRING' can be used for the purpose of capturing the output.
This interpolates the STRING and executes it as system command and returns the value as output of command execution. In scalar Context it returns the STDOUT value as a string( may be multi line).
STDOUT is referred as 1 while STDERR as 2.

Usage:
# To Captures both STDOUT and STDERR, Redirects STDERR(2) to STDOUT(1)
$output = `cmd 2>&1`;
 
# Captures Only STDOUT, STDERR is discarded ( STDERR is redirected to null) 
$output = `cmd 2>/dev/null`;  
 
# To capture only STDERR, and discard STDOUT, Order is Important
$output = `cmd 2>&1 1>/dev/null`;  
Using this following command you can redirect STDOUT and STDERR outputs to different files.
system("perl test.pl 1>test.stdout 2>test.stderr");

Check "`STRING`" in perlop (Part of perldoc) for more detail.

No comments:

Post a Comment