in reply to Shortening "$bar{foo} if exists $bar{foo}"?
I'm surprised that I didn't find a module like this on CPAN...
And now you can just: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;
If anyone wants to add documentation, tests, etc to the above module and load it into CPAN as yours, be my guest.tie my %bar, 'Tie::HashDefaultValue', sub {}; # time passes $bar{foo}->();
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] }
|
---|
In Section
Seekers of Perl Wisdom