gpt4 book ai didi

Perl: mock -d -f 和 friend 。如何将它们放入 CORE::GLOBAL

转载 作者:行者123 更新时间:2023-12-04 00:29:41 24 4
gpt4 key购买 nike

CORE 文档向我展示了如何愉快地模拟各种内置的 Perl 函数。但是,我不确定如何替换 '-d' &c。用我的方法。所以这实际上只是一个关于如何在 CORE::GLOBAL 中用破折号替换函数的问题。

手动引用会很好。

package Testing::MockDir;

use strict;
use warnings;
use Exporter();
use Symbol 'qualify_to_ref';

*import = \&Exporter::import;

our @EXPORT_OK = qw(SetMockDir UnsetMockDir);

our %EXPORT_TAGS = (
'all' => \@EXPORT_OK,
);

my %path2List = ();
my %handle2List = ();

BEGIN {
*CORE::GLOBAL::opendir = \&Testing::MockDir::opendir;
*CORE::GLOBAL::readdir = \&Testing::MockDir::readdir;
*CORE::GLOBAL::closedir = \&Testing::MockDir::closedir;

######################### the "-" is really the problem here
*CORE::GLOBAL::-d = \&Testing::MockDir::mock_d; # This does not work <<<<<
}

sub mock_d ($) {
die 'It worked';
}

sub SetMockDir {
my ($path, @files) = @_;
$path2List{$path} = [@files];
}

sub UnsetMockDir {
my ($path) = @_;
delete $path2List{$path};
}

sub opendir (*$) {
my $handle = qualify_to_ref(shift, caller);
my ($path) = @_;
return CORE::opendir($handle, $path) unless defined $path2List{$path};
$handle2List{$handle} = $path2List{$path};
return 1;
}

sub readdir (*) {
my $handle = qualify_to_ref(shift, caller);
return CORE::readdir($handle) unless defined $handle2List{$handle};
return shift @{$handle2List{$handle}} unless wantarray;

my @files = @{$handle2List{$handle}};
$handle2List{$handle} = [];
return @files;
}

sub closedir (*) {
my $handle = qualify_to_ref(shift, caller);
return CORE::closedir($handle) unless defined $handle2List{$handle};
delete $handle2List{$handle};
return 1;
}

1;

最佳答案

CORE::GLOBAL 不适用于没有原型(prototype)的东西。我能想到的唯一方法是重写操作码树......这不适合胆小的人。您可以使用 B::Utils 的组合来完成它和 B::Generate和大量的实验。

最简单的做法是使用 File::Temp根据您的喜好制作临时目录结构。

关于Perl: mock -d -f 和 friend 。如何将它们放入 CORE::GLOBAL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1954529/

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