Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

recursive exists in perl

by Anonymous Monk
on Dec 09, 2010 at 22:13 UTC ( #876337=perlquestion: print w/ replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I want to do a check like

if (exists $h{A} and exists $h{A}{B} and exists $h{A}{B}{C}) { }

Is there a way to do this more compactly? (Check for existence of a key without auto-vivifying the path?)

Comment on recursive exists in perl
Download Code
Re: recursive exists in perl
by JavaFan (Canon) on Dec 09, 2010 at 22:16 UTC
    Short of using a subroutine that does the same thing, no.
Re: recursive exists in perl
by moritz (Cardinal) on Dec 09, 2010 at 22:20 UTC
    There are modules to do that, for example Data::Diver, or modules that disable autovivification.

    There was also a proposal (and patch) that adds an "exists-or" operator \\ to perl, to parallel the "or" || and "defined-or" // operator. I don't know if it got accepted in the end.

Re: recursive exists in perl
by Anonymous Monk on Dec 09, 2010 at 22:49 UTC
    I'm not sure whether you'd consider this more compact, but it does make it easier to see the path of keys you're checking:
    use List::Util 'reduce'; if (reduce { $a && exists $$a{$b} ? $$a{$b} : undef } \%foo, 'bar', 'baz', 'troz') { }
Re: recursive exists in perl
by ikegami (Pope) on Dec 09, 2010 at 23:02 UTC

      Is that really the case? For example, while the following doesn't autovivify $h{A}{B}{C} it does autovivify $h{A}{B}.

      use Data::Dumper; my %h; if ( exists( $h{A}{B}{C} ) ) { print "Hi mom!\n"; } print Dumper \%h;

      $VAR1 = {
                'A' => {
                         'B' => {}
                       }
              };
      
        use Data::Dumper; my %h; no autovivification; if ( exists( $h{A}{B}{C} ) ) { print "Hi mom!\n"; } print Dumper \%h; __END__ $VAR1 = {};

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://876337]
Approved by Corion
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (8)
As of 2014-08-22 21:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (165 votes), past polls