|
|
Question : perl suppress printing when output to pipe
|
|
|
|
I have written a perl program to print out the result to standard output (STDOUT), it is find when running alone, but when I pipe the output from this perl program to another program in OS level "perl myprogram.pl | grep abc" something like that, the output of the perl program seems to get thru to both STDOUT as well as to the PIPE.
Actually my perl program is as simple as below:- !#/usr/bin/perl
lineNo = 0; $fileName = $ARGV[0];
open(MYINPUTFILE, "-"); while(<MYINPUTFILE>) { # Good practice to store $_ value because # subsequent operations may change it. my($line) = $_;
# Good practice to always strip the trailing # newline from the line. chomp($line);
$lineNo++;
## Field sequence # log_name, line, $1 client_address, $2 rfc1413, $3 user_name, $4 local_time, $5 method, $6 url, $7 protocol, $8 status_code, $9 bytes_sent, $10 referrer, $11 agent, $12 canon_name
if(/^([^ ]+) ([^ ]+) ([^ ]+) \[([^ ]+ [^\]]+)\] \"([^ ]+) (.+) (\w+\/[^\"]+)\" ([^ ]+) ([^ ]+) \"(.*)\" \"(.*)\" \"(.*)\" *$/) { $bytes_sent = ($9=="-") ? 0 : $9; print $fileName,"\t",$lineNo,"\t$1\t$2\t$3\t$4\t$5\t$6\t$7\t$8\t",$bytes_sent,"\t$10\t$11\t$12\n"; } else { if(/^([^ ]+) ([^ ]+) ([^ ]+) \[([^ ]+ [^\]]+)\] \"([^ ]+) (.+)\" ([^ ]+) ([^ ]+) \"(.*)\" \"(.*)\" \"(.*)\" *$/) { $bytes_sent = ($8=="-") ? 0 : $9; print $fileName,"\t",$lineNo,"\t$1\t$2\t$3\t$4\t$5\t$6\t-\t$7\t",$bytes_sent,"\t$9\t$10\t$11\n"; } else { print STDERR "\tline $lineNo not match : $line"; } } }
Which it did read in apache combined log from STDIN and tab delimit the output to STDOUT and print our lines contain errors to STDERR.
What can I do in order to suppress the output to STDOUT when I pipe the output to another program on OS level ?
BTW, the error also doesn't seems to get to STDERR when I "perl myprogram.pl | grep abc 2> abc.err", all error also goes to STDOUT instead of STDERR and thus the abc.err is empty.
|
|
|
|
Answer : perl suppress printing when output to pipe
|
|
As STDOUT is sent to the pipe that would be expected. STDERR normaly only goed to the terminal.
to catch YOUR ourput to abc.err you need: ---8<--- perl myprogram.pl 2>abc.err | grep abc ---8<--- Otherwise the stderr from grep is sent to abc.err to catch the stderr also in a file you NEED to use a different file and merge that later.
|
|
|
|