Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
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
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;
      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 studying the Monastery: (9)
As of 2015-07-28 07:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (252 votes), past polls