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;
You have not 1, but 2 problems here, because this is what you are doing:
( $agent->get_basic_credentials() ) = _user_agent_get_basic_credentials_patch();
on both sides cases, you're calling the subs instead of simply referring to them.
assign the result of
'_user_agent_get_basic_credentials_patch'
to the value that was returned from
'get_basic_credentials';
Equivalent logic :
{
package FooBar;
sub foo(){
return 5;
}
1;
}
my $x = bless( {}, "FooBar" );
sub baz(){
return 1;
}
$x->foo() = baz();
# 5 = 1;
So its no wonder its complaining.
Your "fixed" code in your answer is also wrong, for the same reason, with another problem you may not realise:
$agent->{get_basic_credentials} = _user_agent_get_basic_credentials_patch;
This is rather flawed logic thinking it works like you think it does.
What it is really doing, is:
1. Dereference $agent, which is a HashRef
2. Set the hash-key 'get_basic_credentials' to the result from _user_agent_get_basic_credentials_patch
You didn't assign any function at all.
{
package FooBar;
sub foo(){
return 5;
}
1;
}
my $x = bless( {}, "FooBar" );
sub baz(){
return 1;
}
$x->{foo} = baz();
# $x is now = ( bless{ foo => 1 }, "FooBar" );
# $x->foo(); # still returns 5
# $x->{foo}; # returns 1;
Monkey patching is rather evil of course, and I have not myself seen how to override a method on a singular instance of something like that.
However, what you can do is this:
{
no strict 'refs';
*{'LWP::UserAgent::get_basic_credentials'} = sub {
# code here
};
}
Which will globally replace the get_basic_credentials code sections behaviour ( I might be wrong somewhat, somebody correct me )
If you really need to do it on a per-instance basis you could probably do a bit of class inheritance and just build a derived class instead, and/or dynamically create new packages.