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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|