Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

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 the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (4)
As of 2016-10-22 02:14 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (291 votes). Check out past polls.