我怎样才能摆脱 Perl 中的 STDERR
我正在 Perl 中使用一些系统命令。
在下面的情况下,我得到的输出如下:
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
虽然其他答案对于您提出的确切技术问题是正确的,但您还应该考虑不要在 Perl 中编写有效的 shell 脚本。
您应该使用 Perl 本机方法来获取文件列表(例如
glob()
或File::Find
),而不是调用反引号的ls
。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()
orFile::Find
) instead of calling a backtickedls
.将 STDERR 重定向到空设备:
Redirect STDERR to the null device:
您可以在子 shell 命令中添加
stderr
重定向:You can add
stderr
redirection in your subshell commands:查看 perlfaq8< /a>.如果您不关心它是
STDOUT
还是STDERR
,则可以将两者都重定向到STDOUT
。就您而言,您可能只想摆脱
STDERR
:但是,我同意 DVK 的回答。使用外部命令来获取文件列表似乎很愚蠢。您应该使用 File::Find。这样您就可以在发生故障时使用 Perl 的正常错误处理。
Check out perlfaq8. If you don't care if it's
STDOUT
orSTDERR
, you can get both redirected toSTDOUT
.In your case, you probably just want to get rid of
STDERR
:However, I agree with DVK's answer. Using an external command to get a list of files just seems silly. You should use File::Find. This way you can use Perl's normal error handling in case something fails.
创建一个新的警告挂钩,然后对消息执行某些操作,存储它,忽略它等等......
Create a new warn hook, then do something with the message, store it, ignore it etc...
您可以将
stderr
重定向到/dev/null
,如下所示:You can redirect the
stderr
to/dev/null
as:子 shell 将继承父级的 STDERR,因此如果您想在全局级别上执行此操作,可以这样做:
Subshells will inherit the parent's STDERR, so if you want to do it on a global level, you can do this:
通常您还想稍后恢复
STDERR
。我这样做是这样的:OR
您可以使用
Capture::Tiny
模块,这使得它更容易阅读和更便携。Often you also want to restore
STDERR
later. I do this like this:OR
You can use the
Capture::Tiny
module which makes it easier to read and more portable.以下是如何抑制 STDERR、捕获关闭时发生的错误消息、恢复 STDERR 以及报告任何捕获的错误消息。
Here's how you can suppress STDERR, capture error messages that occur while turned off, restore STDERR, and report back any captured error messages.