kennethk has asked for the wisdom of the Perl Monks concerning the following question:
This is a follow up to Localizing hash keys in an AoH. tobyink's suggestion of guards has worked well, until I discovered I'd naively used the code in a case where I actually needed to delete the hash key/value pair when scope exited, instead of just restoring a value. I cobbled together the code
which performs the necessary function, albeit in a clunkier-feeling way. The target hashrefs in the array are cross-referenced in a couple ways, so I really do need to localize the value in the hashref (as opposed to localizing an array slice and inserting duplicate hashrefs). Any ideas? Obviously this is more academic, since I have functioning code.sub localised_hashvalue { package localised::hashvalue; my ($ref, $key, $value) = @_; my $exist = exists $ref->{$key}; my $old = $ref->{$key}; $ref->{$key} = $value; return bless [$ref, $key, $exist, $old]; sub DESTROY { my ($ref, $key, $exist, $old) = @{+shift}; $ref->{$key} = $old; delete $ref->{$key} if !$exist; } }
#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Localizing hash keys in an AoH, continued
by rjt (Curate) on Jul 22, 2013 at 19:12 UTC | |
by kennethk (Abbot) on Jul 22, 2013 at 21:04 UTC |
Back to
Seekers of Perl Wisdom