1

の呼び出し_function_used_by_exported_functionに対してのみを再定義することは可能ですか?exported_functionsecond_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();
4

1 に答える 1

8

sub _function_used_by_exported_functionの内部をローカルで再定義できます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();

ブライアン・ド・フォイのマスタリングPerlsub second_routine 、第10章(161ページ)から内部のtypeglob割り当てを解除しました。subはtypeglobに割り当てることで再定義され、そのcoderef部分のみが置き換えられます。私は現在のブロック内でのみそれを行うために使用します。そうすれば、出力でわかるように、外の世界は変更の影響を受けません。local

1051
1000021
1051
于 2012-08-02T08:26:43.270 に答える