in reply to Autovivification with hash of hashes

exists tests for the existance of the last part of the expression. It will autovivify any earlier parts in the process. You need to code

<p><code> if(exists($foo{bar}{baz})) { print "\$foo{bar}{baz} exists\n"; }

as

if(exists($foo{bar}) and exists($foo{bar}{baz})) { print "\$foo{bar}{baz} exists\n"; }

to prevent it.


Examine what is said, not who speaks.

The 7th Rule of perl club is -- pearl clubs are easily damaged. Use a diamond club instead.

Replies are listed 'Best First'.
Re: Re: Autovivification with hash of hashes
by Cabrion (Friar) on Jan 26, 2003 at 01:38 UTC
    The use of eval might be in order here to programtically build up:

    if(exists($foo{bar}) and exists($foo{bar}{baz})) { print "\$foo{bar}{baz} exists\n"; }

    by doing soemthing like this:

    my @levels = qw/bar baz/; foreach(@levels) { $_ = 'exists('.$_.')'; } my $code = '('.join(' and ', @levels).')'; #$code is now: (exists($foo{bar}) and exists($foo{bar}{baz}) if (eval $code) { #do whatever }

    Note that the order of @levels is important.

      No need to pay the penalty of eval, see Aristotle's exists_novivify sub


      Examine what is said, not who speaks.

      The 7th Rule of perl club is -- pearl clubs are easily damaged. Use a diamond club instead.