Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: checking if hashref value exists based on a dynamic array

by pc88mxer (Vicar)
on Aug 08, 2008 at 06:19 UTC ( #703053=note: print w/ replies, xml ) Need Help??


in reply to checking if hashref value exists based on a dynamic array

sub deep_exists { my $hash = shift; return 0 if @_ == 0; while (@_ > 1) { $hash = $hash->{shift} or return 0; } return exists $hash->{$_[0]}; } if (deep_exists(\%hash, 'a', 't', 'etc')) { ... }


Comment on Re: checking if hashref value exists based on a dynamic array
Download Code
Replies are listed 'Best First'.
Re^2: checking if hashref value exists based on a dynamic array
by kyle (Abbot) on Aug 08, 2008 at 15:15 UTC

    Did you try this? Generally, "$hash->{shift}" is interpreted as "$hash->{'shift'}", but I think you mean "$hash->{shift()}".

    Also, this and other solutions I've seen here seem to ignore the possibility of running into a non-hash somewhere along the way.

    use Test::More 'tests' => 5; sub deep_exists { my $hash = shift; my $key = shift; return 0 if ( ref $hash ne ref {} || ! exists $hash->{$key} ); return deep_exists( $hash->{$key}, @_ ) if @_; return 1; } my %h; $h{there}{also}{yes} = 1; $h{hash}{shift}{scalar} = 1; ok( deep_exists( \%h, 'there', 'also', 'yes' ), 'there also yes' ); ok( deep_exists( \%h, 'there', 'also' ), 'there also' ); ok( ! deep_exists( \%h, 'there', 'also', 'no' ), 'there also no' ); ok( deep_exists( \%h, 'hash', 'shift', 'scalar' ), 'hash shift scalar' + ); ok( ! deep_exists( \%h, 'hash', 'shift', 'scalar', 'hash' ), 'hash shift scalar hash' );

      Also, this and other solutions I've seen here seem to ignore the possibility of running into a non-hash somewhere along the way

      Mine (Data::Diver) checks.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://703053]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (10)
As of 2015-07-29 16:50 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 (265 votes), past polls