Here's a general routine that will tell you if a particular branch of a hash exists. In otherwords, if you have this:
$hash{ foo }{ bar }{ baz }
It can be a pain to check for the existence of every single key.
use strict; use warnings; use Data::Dumper; my %hash = ( one => { test => 3 }, two => { Ovid => { is => { a => 'fool' } } } ); if ( hash_branch_exists( \%hash, qw/ one test / ) ) { print "Good\n"; } else { print "Bad\n"; } if ( hash_branch_exists( \%hash, qw/ Ovid is a fool / ) ) { print "Good\n"; } else { print "Bad\n"; } if ( hash_branch_exists( \%hash, qw/ two Ovid Is a / ) ) { print "Good\n"; } else { print "Bad\n"; } sub hash_branch_exists { my ( $hash_ref, @fields ) = @_; foreach ( @fields ) { return 0 if ref $hash_ref ne 'HASH'; return 0 if ! exists $hash_ref->{ $_ }; $hash_ref = $hash_ref->{ $_ }; } return 1; }
Cheers,
Ovid
Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.
In reply to (Ovid) Re: Check for existance in a hash of hashes
by Ovid
in thread Check for existance in a hash of hashes
by Perl_User
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |