in reply to Changing Local Variable Out of Context
Yes, with PadWalker it's possible to mess with such internals. See demo.
But as Toby already said, it's probably not a good idea especially for production code.
NB: After calling your patched sub, you'll change $varry for it's whole (file?) scope in that module. This can lead to very unfortunate side effects, if carelessly done.
use v5.12.0; use warnings; # ========= mock original module BEGIN { package zor; my $varry = "DEFAULT"; sub lol { $varry = 'OLD'; return 'whatever'; } sub get_varry { return $varry } # ========= old behaviour warn get_varry; warn lol(); warn get_varry; } package main; # ========= monkey patch sub { package zor; use PadWalker qw/closed_over/; my ($h_closure,$s_varry); # ===== get scalar ref of varry BEGIN { $h_closure = closed_over(\&lol); $s_varry = $h_closure->{'$varry'}; } # ===== new sub no warnings 'redefine'; sub lol { $$s_varry = 'NEW'; return 'whatever'; } } # ========= new behaviour warn zor::lol(); warn zor::get_varry; # OOPS
DEFAULT at d:/Perl/pm/change_my.pl line 21. whatever at d:/Perl/pm/change_my.pl line 22. OLD at d:/Perl/pm/change_my.pl line 23. whatever at d:/Perl/pm/change_my.pl line 54. NEW at d:/Perl/pm/change_my.pl line 55.
changed code to better demonstrate side effects on $varry
Cheers Rolf
(addicted to the 𐍀𐌴𐍂𐌻 Programming Language :)
Wikisyntax for the Monastery
|
---|