Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

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


Comment on Re: Shortening "$bar{foo} if exists $bar{foo}"?
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://296749]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (13)
As of 2014-09-02 07:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (20 votes), past polls