Is it possible to redefine subroutines to be localized for a part of the code?

烂漫一生 提交于 2020-01-05 06:45:06

问题


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();

回答1:


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();

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


来源:https://stackoverflow.com/questions/11773234/is-it-possible-to-redefine-subroutines-to-be-localized-for-a-part-of-the-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!