以下脚本会创建一个名为“input.gz”的 gzip 文件。然后脚本尝试使用 gzip -dc
打开“input.gz”。直观地说,如果提供了错误的输入文件名,则应该触发 die
。但是,如以下脚本所示,即使提供了错误的输入文件名(“inputx.gz”),程序也不会死
:
use warnings;
use strict;
system("echo PASS | gzip -c > input.gz");
open(IN,"-|","gzip -dc inputx.gz") || die "can't open input.gz!";
print STDOUT "die statment was not triggered!\n";
close IN;
上面脚本的输出是
die statment was not triggered!
gzip: inputx.gz: No such file or directory
我的问题是:为什么 die
语句没有被触发,即使 gzip
因错误退出?当给出错误的文件名时,如何使 die
语句触发?
最佳答案
它被埋在 perlipc ,但这似乎是相关的(强调):
Be careful to check the return values from both open() and close(). If you're writing to a pipe, you should also trap SIGPIPE. Otherwise, think of what happens when you start up a pipe to a command that doesn't exist: the open() will in all likelihood succeed (it only reflects the fork()'s success), but then your output will fail--spectacularly. Perl can't know whether the command worked, because your command is actually running in a separate process whose exec() might have failed. Therefore, while readers of bogus commands return just a quick EOF, writers to bogus commands will get hit with a signal, which they'd best be prepared to handle.
使用 IO::Uncompress::Gunzip
改为读取 gzip 文件。
关于Perl: `die` 在使用 gzip 打开不存在的 gz 文件时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59098349/