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
|