我正在尝试以猴子补丁(duck-punch :-)一个LWP :: UserAgent实例,像这样:
sub _user_agent_get_basic_credentials_patch { return ($username,$password); } my $agent = LWP::UserAgent->new(); $agent->get_basic_credentials = _user_agent_get_basic_credentials_patch;
这不是正确的语法 – 它产生:
Can’t modify non-lvalue subroutine
call at [module] line [lineno].
我记得(从Perl编程),调度查找是基于祝福的包(ref($ agent)),我相信)动态执行,所以我不知道猴子修补程序如何甚至可以工作,而不影响保佑的包。
我知道我可以对UserAgent进行子类化,但是我更喜欢更简洁的猴子补丁方法。同意成年人和你有什么;-)
解决方法
如果动态范围(使用本地)不令人满意,您可以自动化自定义软件包重现技术:
MONKEY_PATCH_INSTANCE: { my $counter = 1; # could use a state var in perl 5.10 sub monkey_patch_instance { my($instance,$method,$code) = @_; my $package = ref($instance) . '::MonkeyPatch' . $counter++; no strict 'refs'; @{$package . '::ISA'} = (ref($instance)); *{$package . '::' . $method} = $code; bless $_[0],$package; # sneaky re-bless of aliased argument } }
用法示例:
package Dog; sub new { bless {},shift } sub speak { print "woof!\n" } ... package main; my $dog1 = Dog->new; my $dog2 = Dog->new; monkey_patch_instance($dog2,speak => sub { print "yap!\n" }); $dog1->speak; # woof! $dog2->speak; # yap!