agname has asked for the wisdom of the Perl Monks concerning the following question:
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: caching hashrefs in state
by Laurent_R (Canon) on Apr 22, 2014 at 18:58 UTC | |
|
Re: caching hashrefs in state
by Anonymous Monk on Apr 22, 2014 at 19:26 UTC | |
by AnomalousMonk (Archbishop) on Apr 22, 2014 at 22:10 UTC | |
|
Re: caching hashrefs in state
by mhearse (Chaplain) on Apr 22, 2014 at 22:08 UTC | |
|
Re: caching hashrefs in state
by Anonymous Monk on Apr 23, 2014 at 02:40 UTC | |
|
Re: caching hashrefs in state
by kcott (Archbishop) on Apr 23, 2014 at 11:02 UTC |