I would like to run a external command in perl and filter some of the lines.
I don’t know how to filter the lines that go to stderr. I have the following code right now:
#!/usr/bin/env perl
use File::Spec;
#open STDERR, '>', File::Spec->devnull() or die "could not open STDERR: $!\n";
open(FILEHANDLE, '-|', 'Mycmd') or die "Cannot fork: $!\n";
open(STDERR, ">&FILEHANDLE");
while(defined(my $line = <FILEHANDLE>)) {
chomp($line);
if( $line =~ m/text1/ or
$line =~ m/text2/ or
$line =~ m/text3/
) {
# do nothing
}
else {
print "$line\n";
}
}
close FILEHANDLE or die "child error: $!\n";
the line
open(STDERR, ">&FILEHANDLE");
is where I try to redirect the stderr to be able to process it with stdout but it doesn’t work.
The solution would have to work in windows.
A shell redirect in the argument to
opencan help here:Now
FILEHANDLEwill see each line of both the standard output and the standard error fromMycmd.To use multi-argument
openand redirect output, you have to be more deliberate. SayMycmdisOpening
"-|"gives us the standard output only, so if we runThe output is
Notice that the standard output from
Mycmdpassed through the driver program but not its standard error. To get both, you have to mimic the shell’s redirection.Now the output is