See the other replies for why Perl does this. I have a subroutine I use when I want to get a value from a nested structure only if it exists. You can modify this to do the existence check only if you need that.

use Carp; sub safe_get { my $handle = shift; my $ptr = $handle; for (my $i = 0; $i < @_; $i++) { my $key = $_[$i]; # Handle each type my $type = ref $ptr; if (not defined $type) { croak "Not a reference.\n"; } elsif ($type eq 'HASH') { return undef unless exists $ptr->{$key}; $ptr = $ptr->{$key}; } elsif ($type eq 'ARRAY') { croak "Non numeric array index '$key'." unless $key =~ m/^\+?\d+$/; croak "Bad array thing '$key'." unless $key >= 0; return undef unless $key < @$ptr; $ptr = $ptr->[$key]; } else { croak "Unable to handle type '$type'"; } # Is this the end? return $ptr if $i == @_ - 1; } } # Usage my %foo = {bar => [1, {baz => 'xyzzy'}] }; my $value1 = safe_get(\%foo, 'bar', 1, 'baz'); my $value2 = safe_get(\%foo, 'bar', 2, 'baz'); # $value1 is 'xyzzy', $value2 is undef

-ben


In reply to Re: Re: Re: exists() unexpected behavior by knobunc
in thread exists() unexpected behavior by Richard

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.