Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Re: Default Hash Key

by TGI (Parson)
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

Replies are listed 'Best First'.
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?

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (6)
As of 2018-06-18 10:05 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (109 votes). Check out past polls.