Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
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
Replies are listed 'Best First'.
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 = {};
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 JavaFan (Canon) on Dec 09, 2010 at 22:16 UTC
    Short of using a subroutine that does the same thing, no.

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 romping around the Monastery: (11)
As of 2015-07-30 09:47 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 (270 votes), past polls