Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Re: Shortening "$bar{foo} if exists $bar{foo}"?

by tilly (Archbishop)
on Oct 05, 2003 at 18:43 UTC ( #296749=note: print w/replies, xml ) Need Help??

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] }

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://296749]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (8)
As of 2017-05-23 18:06 GMT
Find Nodes?
    Voting Booth?