Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: caching hashrefs in state

by Anonymous Monk
on Apr 23, 2014 at 02:40 UTC ( [id://1083261]=note: print w/replies, xml ) Need Help??


in reply to caching hashrefs in state

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

$ 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.
state $f, once initialized deoesn't get reinitialized ,  state $f = $_[0]; only executes ONCE the very first time

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.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2024-04-19 14:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found