是否可以重新定义要在部分代码中本地化的子例程? [英] Is it possible to redefine subroutines to be localized for a part of the code?

查看:88
本文介绍了是否可以重新定义要在部分代码中本地化的子例程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以仅针对second_routine中的exported_function调用重新定义_function_used_by_exported_function?

Is it possible to redefine the _function_used_by_exported_function only for the exported_function call in the second_routine?

#!/usr/bin/env perl
use warnings; 
use strict;
use Needed::Module qw(exported_function);


sub first_routine {
    return exported_function( 2 );
}

no warnings 'redefine';

sub Needed::Module::_function_used_by_exported_function {
    return 'B';
}

sub second_routine {
    return exported_function( 5 );
}

say first_routine();
say second_routine();

推荐答案

您可以在sub second_routine内部本地重新定义sub _function_used_by_exported_function.

You can locally redefine the sub _function_used_by_exported_function inside your sub second_routine.

package Foo;
use warnings; 
use strict;
use base qw(Exporter);
our @EXPORT = qw(exported_function);

sub exported_function {
  print 10 ** $_[0] + _function_used_by_exported_function();
}

sub _function_used_by_exported_function {
  return 5;
}

package main;
use warnings; 
use strict;

Foo->import; # "use"

sub first_routine {
    return exported_function( 2 );
}

sub second_routine {
    no warnings 'redefine';
    local *Foo::_function_used_by_exported_function = sub { return 2 };
    return exported_function( 5 );
}

say first_routine();
say second_routine();
say first_routine();

我从brian d foy的 Mastering Perl ,第161页的第10章中取消了sub second_routine中的typeglob分配.通过分配给typeglob来重新定义该子项,该子项仅替换了它的coderef部分. .我使用 local 仅在当前块内执行此操作.这样一来,外部世界就不会受到更改的影响,正如您在输出中看到的那样.

I lifted the typeglob assignment inside sub second_routine from brian d foy's Mastering Perl, Chapter 10 on page 161. The sub is redefined by assigning to the typeglob, which only replaces the coderef part of it. I use local to only do that inside the current block. That way, the outside world is not affected by the change, as you can see in the output.

1051
1000021
1051

这篇关于是否可以重新定义要在部分代码中本地化的子例程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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