2012-08-02 2 views
1

second_routineexported_function 전화에 대해서만 _function_used_by_exported_function을 재정의 할 수 있습니까?코드의 일부로 현지화 될 서브 루틴을 재정의 할 수 있습니까?

#!/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(); 
+3

그렇게 할 수 있지만 좋지 않습니다. 우리가 사용하는 것을 설명하면 아마 더 좋은 방법을 찾을 수있을 것입니다. – Schwern

+0

약간의 속도 향상이 있었을 것입니다. 그러나 나는이 경우 불쾌한 코드를 원하지 않으므로 사용하지 않을 것이다. –

답변

8

당신은 로컬 sub second_routine 내부의 sub _function_used_by_exported_function을 다시 정의 할 수 있습니다.

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

나는 서브가 만의 코드 참조 부분을 대체하는 타입 글로브에 할당하여 재정의 161 페이지에 브라이언 d 개의 포이의 마스터 링 펄, 10 장에서 sub second_routine 내부의 타입 글로브 할당을 해제. 나는 현재 블록 안에서만 이것을 수행하기 위해 local을 사용한다. 그렇게하면 출력에서 ​​볼 수 있듯이 바깥 세상은 변화의 영향을받지 않습니다.

1051 
1000021 
1051 
관련 문제