", "$filename") or die "Could not open file $fi-6ren">
gpt4 book ai didi

perl - 在 Perl 中写入文件时测试错误处理的最简单方法是什么?

转载 作者:行者123 更新时间:2023-11-28 19:56:23 25 4
gpt4 key购买 nike

我有一个糟糕的标准 Perl 文件编写代码(希望)有足够的错误处理,类型:

open(my $fh, ">", "$filename") or die "Could not open file $filname for writing: $!\n";
# Some code to get data to write
print $fh $data or die "Could not write to file $filname: $!\n";
close $fh or die "Could not close file $filname afterwriting: $!\n";
# No I can't use File::Slurp, sorry.

(我只是凭内存写了这段代码,请原谅任何错别字或错误)

在第一个“die”行测试错误处理有点容易(例如,创建一个与您计划写入的名称相同的不可写文件)。

如何测试第二(打印)和第三(关闭)“die”行中的错误处理?

我知道在关闭时引发错误的唯一方法是在写入时用完文件系统上的空间,这作为测试并不容易。

我更喜欢集成测试类型的解决方案而不是单元测试类型(这将涉及在 Perl 中模拟 IO 方法)。

最佳答案

使用错误的文件句柄会使它们都失败

use warnings;
use strict;
use feature 'say';

my $file = shift || die "Usage: $0 out-filename\n";

open my $fh, '>', $file or die "Can't open $file: $!";

$fh = \*10;

say $fh 'writes ok, ', scalar(localtime) or warn "Can't write: $!";

close $fh or warn "Error closing: $!";

打印

say() on unopened filehandle 10 at ...Can't write: Bad file descriptor at ...close() on unopened filehandle 10 at ...Error closing: Bad file descriptor at ...

如果您不想看到 perl 的警告,请使用 $SIG{__WARN__} 捕获它们并将您的消息打印到文件(或 STDOUT),例如。

关于perl - 在 Perl 中写入文件时测试错误处理的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55927880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com