Hi,

I have been using state to cache a hashref and I am unsure whether this is good usage. It does however work.

Here is an example of usage:

#!/usr/bin/perl use v5.10; use strict; use warnings; sub example_sub { my $cfg = cfg_cache(); say $cfg->{x}; } sub cfg_cache { state $cfg = shift; return $cfg; } my $cfg = { x => "cat"}; cfg_cache($cfg); ## "cat" gets printed example_sub(); ## "mouse" gets printed. $cfg->{x} = "mouse"; example_sub(); ## but if I reset $cfg "mouse" still gets printed $cfg = { x => "rat"}; example_sub();

example_sub() always gets whatever the current contents of $cfg should be as long as $cfg is not reset.

Without reading from cfg_cache() example_sub() has no access to the $cfg hashref.

The state perldoc says "variables will never be reinitialized" but it doesn't cover what happens if the variable is a reference.

Is this good practice?

I am using Perl 5.18 on Debian Unstable but using state this ways works from v5.10


In reply to 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.