Perl:嘲笑-d -f和朋友.如何将它们放入CORE :: GLOBAL [英] Perl: mocking -d -f and friends. How to put them into CORE::GLOBAL

查看:57
本文介绍了Perl:嘲笑-d -f和朋友.如何将它们放入CORE :: GLOBAL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The CORE documentation has shown me how to merrily mock various built Perl functions. However, I'm not really sure how to replace '-d' &c. with my methods. So this is really just a question on how do i replace a function with a dash in it in 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;

推荐答案

这可能是不可能的. perlsub 部分. html#Overriding-Built-in-Functions"rel =" noreferrer>覆盖内置函数对于可以覆盖哪些函数含糊不清. 很多"可以,一些"不能,但是除了少数示例之外,没有确定的列表.

It may not be possible. The perlsub section on Overriding Built-in Functions is vague about which functions can be overridden. "Many" can, "some" can't, but aside from a handful of examples there's no definitive list.

通常,我会尝试这样做:

Normally, I'd try this:

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

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

which isn't a syntax error, but doesn't have the effect of overriding -d.

这篇关于Perl:嘲笑-d -f和朋友.如何将它们放入CORE :: GLOBAL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆