Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Default Hash Key

by TGI (Vicar)
on May 02, 2008 at 00:57 UTC ( #684067=note: print w/ replies, xml ) Need Help??


in reply to Default Hash Key

Use a tied hash.

package DefaultHash; sub TIEHASH { my $class = shift; my $default = shift; my $self; $self->{_DEFAULT} = $default; $self->{_HASH} = {}; return bless $self, $class; } sub FETCH { my $self = shift; my $key = shift; return exists $self->{_HASH}{$key} ? $self->{_HASH}{$key} : $self->{_DEFAULT} } sub EXISTS { my $self = shift; my $key = shift; return exists $self->{_HASH}{$key}; } sub FIRSTKEY { my $self = shift; my $foo = keys %{$self->{_HASH}}; # Reset each return each %{$self->{_HASH}}; } sub NEXTKEY { my $self = shift; return each %{$self->{_HASH}}; } sub CLEAR { my $self = shift; $self->{_HASH} = {}; } sub DELETE { my $self = shift; my $key = shift; return delete $self->{_HASH}{$key}; } sub STORE { my $self = shift; my $key = shift; my $value = shift; $self->{_HASH}{$key} = $value; } package main; tie( my %hash, 'DefaultHash', 'a default value' ); %hash = ( a => 1, b => 2, c => 3 ); print "$_ => $hash{$_}\n" for qw(a b c d);


TGI says moo


Comment on Re: Default Hash Key
Download Code
Re^2: Default Hash Key
by ikegami (Pope) on May 02, 2008 at 01:09 UTC
    That's way way longer than it needs to be (and thus more error-prone and harder to maintain).

      Thanks for the pointer to Tie::ExtraHash.

      I wonder how much of the "new" goodness added in Perl 5.8 I still haven't found...


      TGI says moo

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (6)
As of 2014-09-03 03:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (35 votes), past polls