Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

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

by exilepanda (Friar)
on Oct 06, 2012 at 08:36 UTC ( [id://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!

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
Domain Nodelet?
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?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (4)
As of 2024-04-19 20:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found