Perl: `die` 在使用 gzip 打开不存在的 gz 文件时不起作用

标签 perl die

以下脚本会创建一个名为“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/

相关文章:

php - PHP die() 返回什么

php - 使用 PHP die() 时回显 <div class> 不起作用;

netlogo - 如果其中一个链接消失,如何更改海龟的属性?

perl - cpan 忽略 makepl_arg 和 mbuild_arg

regex - Perl:如何在正则表达式中使用字符串变量作为搜索模式和替换

perl - Perl 中的嵌套子例程和作用域

php - 样式die()错误消息

jQuery:绑定(bind)和取消绑定(bind)实时点击事件

Perl 按位运算给出意想不到的结果

perl - 如果我有 t 统计量和 d.f.,我如何计算 p 值? (在 Perl 中)?