in reply to Making a failed hash lookup return something other than undef

With all of the solutions you provided in your original question, "auto vivification" will cause Perl to create that hash element you're testing, and just leaves its value undefined. Thus, the hash grows, and the key exists, though its value is undef. That's a problem.

How about this?

$var = exists( $hash{'key'} ) ? $hash{'key'} : "non-existant";

That won't trigger auto-vivification of the hash key. And it accomplishes your goal of reliably returning either the key or something else if the key doesn't exist. Always use exists to check existance of a hash key. defined (or checking for a value) doesn't do what you want.


Dave


"If I had my life to live over again, I'd be a plumber." -- Albert Einstein

Replies are listed 'Best First'.
Re: Re: Making a failed hash lookup return something other than undef
by thelenm (Vicar) on Nov 13, 2003 at 20:09 UTC

    Actually, auto-vivification of hash entries doesn't happen unless you do something like take a reference to the hash entry... for example by referring to something more deeply nested in the non-existent hash entry:

    #!/usr/bin/perl -l my %hash; my $foo = $hash{'foo'}; print exists $hash{'foo'} ? "yes" : "no"; # prints "no" my $bar = $hash{'bar'}->{'xxx'}; print exists $hash{'bar'} ? "yes" : "no"; # prints "yes" my $baz = \$hash{'baz'}; print exists $hash{'baz'} ? "yes" : "no"; # prints "yes"

    -- Mike

    --
    XML::Simpler does not require XML::Parser or a SAX parser. It does require File::Slurp.
    -- grantm, perldoc XML::Simpler

      However, the hash itself may be auto-vivified in spite of using exists().   In fact, the hash will be auto-vivified by the use in exists()!   This may be what davido was thinking about.   Check perlref for examples of how the end-point (the hash element) is protected from auto-vivification by the above constructs, by the leading components of the hash expression are not.