2011-02-25 16 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; 
};