I'm using some system commands in Perl.
In the below case I was getting output as follows:
ls: import-log.*: No such file or directory
ls: error-log.*: No such file or directory
No specified files found for deletion
My code:
sub monthoryear()
{
@importlog = `ls -al import-log.*`;
@errorlog = `ls -al error-log.*`;
}
I don't want to see the following in the output even if there are no files.
ls: import-log.*: No such file or directory &
ls: error-log.*: No such file or directory
You can use Capture::Tiny to capture stdout, stderr or both merged. Show activity on this post. I'm personally a fan of the core module IPC::Open3, though the answer with 2>&1 will get both stderr and stdout in the same stream (and usually good enough).
In Perl, when a perl program starts, these two output channels are represented by two symbols: STDOUT represents the Standard Output, and STDERR represents the Standard Error.
Understanding the concept of redirections and file descriptors is very important when working on the command line. To redirect stderr and stdout , use the 2>&1 or &> constructs.
While the other answers are correct about the exact technical question you asked, you should also consider not writing what is effectively a shell script in Perl.
You should use Perl native methods of getting file list (e.g. glob()
or File::Find
) instead of calling a backticked ls
.
Redirect STDERR to the null device:
use File::Spec;
open STDERR, '>', File::Spec->devnull() or die "could not open STDERR: $!\n";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With