in reply to Re^4: Why does exists cause autovivication?
in thread Why does exists cause autovivication?
It's not that hard.
Either, instead of exists, use Data::Diver (by tye):
$ perl -Mstrict -MData::Diver=Dive -MData::Dumper -wE ' my $h; $h->{foo}->{bar}->{baz} = "qux"; say Dumper $h; say Dive( $h, qw/ foo bar baz / ) ? 1 : 0; say Dive( $h, qw/ foo NOT baz / ) ? 1 : 0; say Dumper $h; ' $VAR1 = { 'foo' => { 'bar' => { 'baz' => 'qux' } } }; 1 0 $VAR1 = { 'foo' => { 'bar' => { 'baz' => 'qux' } } };
Or, if you want to use exists, just test for each level that you are not sure exists before going any deeper:
$ perl -Mstrict -MData::Dumper -wE ' my $h; $h->{foo}->{bar}->{baz} = "qux"; say Dumper $h; say( (exists $h->{foo}->{bar}->{baz}) ? 1 : 0 ); say( (exists $h->{foo}->{NOT} && exists $h->{foo}->{NOT}->{baz}) ? 1 : + 0 ); say Dumper $h; ' $VAR1 = { 'foo' => { 'bar' => { 'baz' => 'qux' } } }; 1 0 $VAR1 = { 'foo' => { 'bar' => { 'baz' => 'qux' } } };
|
|---|