Is this good practice?
not really -- if you're abstracting away a configuration singleton, don't allow direct access to the underlying hash (the state-d hash)
if you're going to allow direct access, just make it our %hash
Also, like the other guy said , state $cfg never gets re-initialized,
the state $cfg inside sub cfg_cache has nothing to do with the my $cfg outside
$state_cfg doesn't get reinitialized, it holds a reference to $my_cfg, if you assign $my_cfg a new reference $state_cfg will not be affected, $state_cfg will still hold the original reference
The state perldoc says "variables will never be reinitialized" but it doesn't cover what happens if the variable is a reference.
Sure it does, a reference is a still just a variable, it won't be reinitialized
state $f, once initialized deoesn't get reinitialized , state $f = $_[0]; only executes ONCE the very first time$ perl -le " use v5.10; sub f { state $f = $_[0]; warn qq{ $f # @_ }; + $f; } f({},$_) for 1 .. 4 " HASH(0x3f9b34) # HASH(0x3f9b34) 1 at -e line 1. HASH(0x3f9b34) # HASH(0x3f9b44) 2 at -e line 1. HASH(0x3f9b34) # HASH(0x3f9b94) 3 at -e line 1. HASH(0x3f9b34) # HASH(0x3f9b44) 4 at -e line 1.
However multiple assignments are multiple
$ perl -le " use v5.10; sub f { state $f; $f = $_[0]; warn qq{ $f # @ +_ }; $f; } f({},$_) for 1 .. 4 " HASH(0x3f9b44) # HASH(0x3f9b44) 1 at -e line 1. HASH(0x3f9b54) # HASH(0x3f9b54) 2 at -e line 1. HASH(0x3f9ba4) # HASH(0x3f9ba4) 3 at -e line 1. HASH(0x3f9b44) # HASH(0x3f9b44) 4 at -e line 1.
In reply to Re: caching hashrefs in state
by Anonymous Monk
in thread caching hashrefs in state
by agname
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |