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.

In reply to Re: caching hashrefs in state by Anonymous Monk
in thread caching hashrefs in state by agname

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.