2011-02-25 20 views
7

我在Perl中使用了一些系统命令。如何摆脱Perl中的STDERR

在下面的情况下,我得到的输出如下:

ls: import-log.*: No such file or directory 

ls: error-log.*: No such file or directory 

No specified files found for deletion 

我的代码:

sub monthoryear() 
{ 

    @importlog = `ls -al import-log.*`; 

    @errorlog = `ls -al error-log.*`; 

} 

我不希望看到下面的输出,即使有没有文件。

ls: import-log.*: No such file or directory & 

ls: error-log.*: No such file or directory 

回答

5

您可以添加stderr重定向在子shell命令:

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

什么如果我想捕获该错误消息? – Sunny 2011-02-25 17:35:54

+0

@Sunny - 在这种情况下,您可以使用文件而不是/ dev/null,只需替换为/ path/to /文件 – justkt 2011-02-25 17:37:02

+0

我可以在变量中获取该文件吗? – Sunny 2011-02-25 17:38:02

1

您可以重定向stderr/dev/null为:

@importlog = `ls -al import-log.* 2> /dev/null`; 

@errorlog = `ls -al error-log.* 2> /dev/null`; 
13

而其他的答案是正确的关于确切你所问的技术问题,你也应该考虑不用Perl编写有效的shell脚本。

您应该使用Perl本机获取文件列表的方法(例如​​3210或File::Find)而不是调用被挑选的ls

+1

这实际上是正确的答案。在Perl中这样做意味着您可以将输出捕获到一个变量中,而无需重定向STDERR,这可能会在远处产生令人毛骨悚然的动作。 – CanSpice 2011-02-25 17:44:57

-1

子shell将继承父的STDERR,所以如果你想要做它在全球范围内,你可以这样做:

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

您应该使用打开的三个参数和File :: Spec来获取空设备: – shawnhcorey 2011-02-25 18:45:10

4

退房perlfaq8。如果你不在乎它是否是STDOUTSTDERR,那么可以将它们重定向到STDOUT

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

在你的情况,你可能只是想摆脱STDERR

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

不过,我同意DVK's answer。使用外部命令获取文件列表看起来很愚蠢。你应该使用File::Find。这种方式可以在出现问题时使用Perl的正常错误处理。

#!/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"; 
5

stderr重定向到空设备:

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

创建一个新的警告钩子,然后做一些事情的消息,存储,忽略等..

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; 
};