Don't ask to ask, just ask PerlMonks

### How do you check if a key exists without creating it ?

by exilepanda (Pilgrim)
 on Oct 06, 2012 at 08:36 UTC Need Help??
exilepanda has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,
```use Data::Dumper;
\$x = {};
1 if ( exists \$x->{W} ) ;
1 if ( defined \$x->{X} ) ;
1 if ( \$x->{Y} ) ;
1 if ( exists \$x->{Y}{X}  ) ;
1 if ( defined \$x->{Z}{A}  );
print Dumper \$x;
[download]```
Result :
```\$VAR1 = {
'Z' => {},
'Y' => {}
};
[download]```
What I don't want is Z, Y create by itself, when I try to check if some keys from inner are existed or not. Can I do that ? Hopefully this won't be the only solution
```if ( \$x->{Y} ) {
if ( \$x->{Y}{Z} ) {
1 if ( \$x->{Y}{Z}{A} ) ;
}
} ; # \$VAR={};
[download]```
Any clues? Thank you very much!

Replies are listed 'Best First'.
Re: How do you check if a key exists without creating it ?
by wind (Priest) on Oct 06, 2012 at 08:43 UTC

You're just falling into autovivification. Check for existence of the lower level first if you don't want it autocreated:

```use Data::Dumper;
\$x = {};
1 if ( \$x->{Y} && exists \$x->{Y}{X}  ) ;
1 if ( \$x->{Z} && defined \$x->{Z}{A}  );
print Dumper \$x;
[download]```
haha.. yes, lesson just learned! Thank you very much! =)
Re: How do you check if a key exists without creating it ?
by Anonymous Monk on Oct 06, 2012 at 08:44 UTC
Well, you start by not creating it :)
```if( exists \$foo->{bar}{anything}{you}{want} ){
}
[download]```

Or

use Data::Diver 'Dive';

```if( my \$want = Dive( \$foo, qw/ bar anything you want / ) ){
...
}
[download]```
THANK YOU IT WORKS PERFECTLY!!! THANK YOU VERY MUCH!!! =D

Log In?
 Username: Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://997601]
Approved by philipbailey
Front-paged by philipbailey
help
Chatterbox?
and the sunlight beams...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (6)
As of 2018-06-18 10:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
Should cpanminus be part of the standard Perl release?

Results (109 votes). Check out past polls.

Notices?