I could have sworn there was a CPAN module that did this. Tie::Hash::Default or something similarly-named. But I can't find it.

Anyway, this isn't too hard to implement with tie:

package Tie::Hash::Default; require Tie::Hash; our @ISA = qw/Tie::ExtraHash/; sub TIEHASH { my ($class, $default) = @_; bless [ {}, $default ] => $class; } sub FETCH { my ($self, $key) = @_; exists $self->[0]->{$key} ? $self->[0]->{$key} : $self->[1]; } ############# package main; ## -1 is the default value for nonexistant keys in %h tie my %h, 'Tie::Hash::Default', -1; $h{foo} = $h{bar} = 1; print "$_ => $h{$_}\n" for qw/foo bar baz/;
Be careful with this though. You have to make sure you initialize hash values that you are going to alter. A lot of magic/useful things depend on the default value being undef:
$h{asdf}++; ## $h{asdf} == 0 $h{jkl} .= "jlk"; ## $h{jkl} eq "-1jkl" use strict; $h{xyz}{blah} = 1; ## Can't use string ("-1") as a HASH ref ..
... although using exists on the tied hash will still work as expected.

blokhead


In reply to Re: Making a failed hash lookup return something other than undef by blokhead
in thread Making a failed hash lookup return something other than undef by jpfarmer

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.