Perl:mocking -d -f和朋友.如何将它们放入CORE :: GLOBAL

前端之家收集整理的这篇文章主要介绍了Perl:mocking -d -f和朋友.如何将它们放入CORE :: GLOBAL前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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;
@H_404_7@解决方法
可能不可能 Overriding Built-in Functions上的 perlsub部分对于哪些功能可以被覆盖是模糊的. “很多”可以,“一些”不能,但除了少数例子之外,没有明确的清单.

通常我会试试这个:

{
    no strict 'refs';
    *{'CORE::GLOBAL::-d'} = \&Testing::MockDir::mock_d;
}

这不是语法错误,但没有覆盖-d的作用.

猜你在找的Perl相关文章