How can I get rid of STDERR in Perl

I use some system commands in Perl.

In the following case, I got the 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 is:

 sub monthoryear() { @importlog = `ls -al import-log.*`; @errorlog = `ls -al error-log.*`; } 

I do not 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 
+7
source share
7 answers

You can add stderr redirection to your subclass commands:

 @importlog = `ls -al import-log.* 2>/dev/null`; @errorlog = `ls -al error-log.* 2>/dev/null`; 
+5
source

While the other answers are correct regarding the exact technical question you asked, you should also consider not writing what is effectively a shell script in Perl.

You should use Perl's built-in methods to get a list of files (e.g. glob() or File::Find ) instead of calling backticked ls .

+13
source

Redirect STDERR to null device:

 use File::Spec; open STDERR, '>', File::Spec->devnull() or die "could not open STDERR: $!\n"; 
+5
source

Check out perlfaq8 . If you do not like if it is STDOUT or STDERR , you can redirect both to STDOUT .

 $output = `$cmd 2>&1`; 

In your case, you probably just want to get rid of STDERR :

 $output = `$cmd 2>/dev/null`; 

However, I agree with the DVK answer. Using an external command to get a list of files just seems silly. You should use File :: Find . That way, you can use normal Perl error handling if something fails.

 #!/usr/bin/perl use strict; use warnings; use File::Find; my @importlog; my @errorlog; find(sub { push @importlog, $File::Find::name if /^import-log\.*/; push @errorlog, $File::Find::name if /^error-log\.*/; }, '.'); print "Import log:\n", join("\n", @importlog), "\n"; print "Error log:\n", join("\n", @errorlog), "\n"; 
+4
source

Create a new warning hook, then do something with the message, save it, ignore it, etc.

 local $SIG{__WARN__} = sub { my $message = shift; ## do nothing to ignore all together ## ignore specific message # warn $message unless $message =~ /No such file or directory/; ## or do something else # die $message ## make fatal # open my $fh, '>', 'file.log'; print $fh $message; }; 
+2
source

You can redirect stderr to /dev/null as:

 @importlog = `ls -al import-log.* 2> /dev/null`; @errorlog = `ls -al error-log.* 2> /dev/null`; 
+1
source

Subshells inherit the parent STDERR, so if you want to do this globally, you can do this:

 open(STDERR,'>/dev/null'); `ls non-existent-file`; `ls non-existent-file2`; `ls non-existent-file3`; `ls non-existent-file4`; `ls non-existent-file5`; 
-one
source

All Articles