Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

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

by exilepanda (Monk)
on Oct 06, 2012 at 08:36 UTC ( #997601=perlquestion: print w/ replies, xml ) 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;
Result :
$VAR1 = { 'Z' => {}, 'Y' => {} };
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={};
Any clues? Thank you very much!

Comment on How do you check if a key exists without creating it ?
Select or Download Code
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;
      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
      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 web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (5)
As of 2014-08-23 11:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (173 votes), past polls