Perl 是否可以为部分代码重新定义要本地化的子例程?

Perl 是否可以为部分代码重新定义要本地化的子例程?,perl,module,subroutine,redefine,Perl,Module,Subroutine,Redefine,是否可以仅为第二个\u例程中的导出的\u函数调用重新定义导出的\u函数所使用的\u函数 #!/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_us

是否可以仅为
第二个\u例程中的
导出的\u函数调用重新定义导出的\u函数所使用的
\u函数

#!/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\u例程中本地重新定义导出的函数所使用的
sub\u函数

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的《精通Perl》(第161页第10章)中删除了
次秒_例程中的typeglob赋值。sub通过指定给typeglob重新定义,typeglob只替换它的coderef部分。我过去只在当前块中执行此操作。这样,外部世界就不会受到变化的影响,正如您在输出中看到的那样

1051
1000021
1051

您可以在
sub second\u例程中本地重新定义导出的函数所使用的
sub\u函数

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的《精通Perl》(第161页第10章)中删除了
次秒_例程中的typeglob赋值。sub通过指定给typeglob重新定义,typeglob只替换它的coderef部分。我过去只在当前块中执行此操作。这样,外部世界就不会受到变化的影响,正如您在输出中看到的那样

1051
1000021
1051

你可以这样做,但这很不愉快。如果你解释一下你用它做什么的话,我们可能会想出一个更好的方法,那就是稍微提高一点速度。但在这种情况下,我不想要令人不快的代码,所以我不会使用它。你可以这样做,但这是令人不快的。如果你解释一下你用它做什么的话,我们可能会想出一个更好的方法,那就是稍微提高一点速度。但在这种情况下,我不想要令人不快的代码,所以我不会使用它。