use strict;
use warnings;
use Data::Dumper;
my $hash_ref = {1 => 2, 3 => 4};
BLOCK: {
local $hash_ref->{1} = 5;
print Dumper $hash_ref;
}
print Dumper $hash_ref;
The clearest documentation on this, IMHO, is Temporary Values via local() in perlsub. Essentially, you can localize any hash or array value, which will be restored once you exit the current scope. This trick is frequently used with the %SIG handlers. When you do the localization, you are localizing the element in the hash that the reference points at.
Update: When to Still Use local() is actually the better doc link for this question.
#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.
| [reply] [d/l] |
| [reply] |
local acts on the value, not the variable. Don't think about it as localizing the hash reference, nor even localizing the hash. If you look at the code I've provided, I have no explicit package variables, and I'm localizing a value stored in an anonymous hash.
The reason for your cited line from the documentation is to try to prevent people from thinking that my and local do anything even remotely similar. (That's a little hyperbole, which I can expound upon as necessary).
Update: Code is worth a thousand words.
use strict;
use warnings;
use Data::Dumper;
my $hash_ref = {1 => 2, 3 => 4};
BLOCK: {
local $hash_ref->{1} = 5;
$hash_ref->{3} = 6;
print Dumper $hash_ref;
}
print Dumper $hash_ref;
Note the localized value associated with the key 1 is restored when you exit the block, but the (unlocalized) value associated with the key 3 is not.
#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.
| [reply] [d/l] [select] |
I'm mostly interesting in localization of variables with lixical scope.
As you already point out, local acts on the symbol table of the respective package, i.e. on global variables. In your case, I don't see a way how you can have a single hash element automatically restored at the end of the block.
If this feature is really important to you, did you consider a package global variable declared with "our" (i.e. a lexically scoped global variable) as an alternative?
However, I personally would restore the hash entries manually at the end of the block.
--
Ronald Fischer <ynnor@mm.st>
| [reply] [d/l] [select] |