Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Default Hash Key

by TGI (Parson)
on May 02, 2008 at 00:57 UTC ( [id://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 (Patriarch) 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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://684067]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (3)
As of 2025-01-18 10:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Which URL do you most often use to access this site?












    Results (56 votes). Check out past polls.