我想模拟 Perl 的
unlink
来测试我的代码是否删除了正确的文件。基于这个问题及其答案,我尝试:
use strict;
use warnings;
use subs 'unlink';
sub mock_unlink {
use Data::Printer; p @_;
return;
}
BEGIN {
no warnings qw/redefine/;
*CORE::GLOBAL::unlink = \mock_unlink;
# *unlink = \mock_unlink;
use warnings;
}
unlink "some file";
但是当我运行这个时,我的模拟函数确实被调用,但参数列表为空。我还收到一条警告,指出
unlink
未定义。
$ perl mcve.pl
[]
Undefined subroutine &main::unlink called at mcve.pl line 17.
我希望它能打印出来
["some file"]
我尝试了注释掉的行
*unlink = \mock_unlink;
,但这并没有改变任何东西。
我需要如何模拟
unlink
来检查我的代码尝试删除哪些文件?
use strict;
use warnings;
use feature 'say';
#use subs 'unlink';
use subs 'mock_unlink'; # but do you really need it?
sub mock_unlink {
say "Want to unlink: @_";
#return; # returns undef ... why?
}
BEGIN {
no warnings qw/redefine/;
*CORE::GLOBAL::unlink = \&mock_unlink;
use warnings; # no need, `no warnings` is scoped to the block
}
unlink "some file";