Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Changing Local Variable Out of Context (updated)

by LanX (Saint)
on Jun 13, 2023 at 13:30 UTC ( [id://11152834]=note: print w/replies, xml ) Need Help??


in reply to Changing Local Variable Out of Context

> Is it even possible?

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.

UPDATE

changed code to better demonstrate side effects on $varry

Cheers Rolf
(addicted to the 𐍀𐌴𐍂𐌻 Programming Language :)
Wikisyntax for the Monastery

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11152834]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (3)
As of 2025-11-14 06:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What's your view on AI coding assistants?





    Results (70 votes). Check out past polls.

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.