in reply to caching hashrefs in state

G'day agname,

Welcome to the monastery.

The "state $cfg" is assigned the "{ x => "cat"}" hashref — it's a reference that will print something like "HASH(0xffffff)". Changing the value of the key "x", doesn't change the reference. The hashref "{ x => "rat" }" is a completely different value (perhaps "HASH(0x777777)") — whatever you do to this has no bearing whatsoever on the "state $cfg". Consider this example:

#!/usr/bin/env perl use 5.010; use strict; use warnings; my $cfg = { x => 'cat' }; say 'INITIAL: ', $cfg; example_sub(); $cfg->{x} = 'mouse'; say 'CHANGE1: ', $cfg; example_sub(); $cfg = { x => 'rat' }; say 'CHANGE2: ', $cfg; example_sub(); sub example_sub { say cfg_cache()->{x}; } sub cfg_cache { state $cfg = $cfg; say 'CACHED: ', $cfg; return $cfg; }

Output:

INITIAL: HASH(0x7ff0f8802ee8) CACHED: HASH(0x7ff0f8802ee8) cat CHANGE1: HASH(0x7ff0f8802ee8) CACHED: HASH(0x7ff0f8802ee8) mouse CHANGE2: HASH(0x7ff0f8829c38) CACHED: HASH(0x7ff0f8802ee8) mouse

Note how CHANGE2 is a different reference from all the others.

This type of code is likely to become bug-ridden and a maintenance nightmare: this is not a good practice!

If you want all changes involving $cfg to be reflected in what's returned from the cache, don't store the hashref reference, store a reference to $cfg itself. Consider this change to cfg_cache():

sub cfg_cache { state $cfg_ref = \$cfg; say 'CACHED: ', $$cfg_ref; return $$cfg_ref; }

Output:

INITIAL: HASH(0x7fd539802ee8) CACHED: HASH(0x7fd539802ee8) cat CHANGE1: HASH(0x7fd539802ee8) CACHED: HASH(0x7fd539802ee8) mouse CHANGE2: HASH(0x7fd539829c38) CACHED: HASH(0x7fd539829c38) rat

Now the final CACHED reference is the same as the CHANGE2 reference. Given the "state $cfg_ref" value (after dereferencing) is identical to the "my $cfg" value, whose scope is the entire script, its use in this fashion is questionable as it appears to serve no useful purpose — why not just use the "my $cfg".

If, on the other hand, you wanted to cache an initial value and allow no changes at all, create a new hashref with the inital keys and values of $cfg:

sub cfg_cache { state $cfg_ref = { %$cfg }; say 'CACHED: ', $cfg_ref; return $cfg_ref; }

Output:

INITIAL: HASH(0x7fd88c002ee8) CACHED: HASH(0x7fd88c029c50) cat CHANGE1: HASH(0x7fd88c002ee8) CACHED: HASH(0x7fd88c029c50) cat CHANGE2: HASH(0x7fd88c029c38) CACHED: HASH(0x7fd88c029c50) cat

Now the CACHED reference is the same throughout; it's also different from whatever the others are. This is potentially a better use than the others.

If you provided a more concrete idea of the context in which you've chosen to use state variables, we could probably provide a better response with respect to whether you're employing good practices.

-- Ken