http://www.perlmonks.org?node_id=296749


in reply to Shortening "$bar{foo} if exists $bar{foo}"?

I'm surprised that I didn't find a module like this on CPAN...
package Tie::HashDefaultValue; require Tie::Hash; @ISA = 'Tie::ExtraHash'; use strict; sub TIEHASH { my ($class, $default) = @_; return bless [{}, $default], $class; } sub FETCH { my ($tied, $key) = @_; if (exists $tied->[0]{$key}) { return $tied->[0]{$key}; } else { return $tied->[1]; } } 1;
And now you can just:
tie my %bar, 'Tie::HashDefaultValue', sub {}; # time passes $bar{foo}->();
If anyone wants to add documentation, tests, etc to the above module and load it into CPAN as yours, be my guest.

PS While writing the above I found a documentation mistake in Tie::Hash. Bug report submitted...

UPDATE: Reading the Tie::Hash source more carefully, I saw that the default TIEHASH function does what mine does, and so that is not needed. If you wish to have people complain about Perl punctuation, here is an amusing implementation of FETCH:

sub FETCH { exists $_[0][0]{$_[1]} ? $_[0][0]{$_[1]} : $_[0][1] }