Is this good practice?
I don't see anything directly wrong with it. It's just not clear to me from what you write whether some other construct might be more fitting in your situation. Maybe this is an XY Problem - what exactly are you trying to achieve by "caching" the config hashref like this? How do you want your code to behave when individual config values are changed, or the entire config is replaced?
state $cfg never gets re-initialized, so it will always refer to the same hash, and cfg_cache() will always return that same hashref. The contents of the config hash being referred to can still be freely manipulated by anyone holding a reference to the original hash (that's what you're seeing when your code prints "mouse") or anyone calling cfg_cache().
Perhaps you have over-simplified your example code a bit but I don't see the difference between your method and using a (readonly) global variable?
If you're interested in protecting the config hash against (accidental) changes, see Readonly and/or lock_keys from Hash::Util.
In reply to Re: caching hashrefs in state
by Anonymous Monk
in thread caching hashrefs in state
by agname
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |