Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Local for lexicals

by Arunbear (Prior)
on Aug 10, 2009 at 17:48 UTC ( [id://787381]=note: print w/replies, xml ) Need Help??


in reply to Local for lexicals

Here's an ugly hack that simulates the my_local construct:
use strict; use warnings; package MyLocal; use PadWalker qw(peek_my); my %old_value; sub new { my $self = shift; my %arg = @_; my $h = peek_my($arg{level}); $arg{h} = $h; bless \%arg; } sub set { my ($self, $variable , $value) = @_; if(! exists $old_value{$variable}) { $old_value{$variable} = ${ $self->{h}{$variable} }; } ${ $self->{h}{$variable} } = $value; } DESTROY { my $self = shift; foreach my $var (keys %old_value) { ${ $self->{h}{$var} } = delete $old_value{$var}; } } package main; my $x = 1; my $f = sub { $x }; { my $loc = MyLocal->new(level => 1); $loc->set('$x' => 2); print $f->(), "\n"; # => 2 } print $f->(), "\n"; # => 1
It uses PadWalker to reach within $f, and an object destructor to restore the original value at the end of scope.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (1)
As of 2024-04-25 19:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found