sub insert_domain { my $cursor = shift; $cursor = $cursor->{$_} ||= {} for @_; $cursor = {}; } insert_domain(\%domain, qw(org perlmonks www));
The only "trick" here is using ||=, which only assigns to a variable if it's false. Since we only add hash references in this hash structure and references are always true, it means we only assign an empty anonymous hash {} to nonexistant values; otherwise, we move the cursor down one level to the already existing subhash.
Update: pg's post compelled me to test mine, and it does work:
insert_domain \%domain, qw(com perlmonks www); insert_domain \%domain, qw(org perlmonks www); insert_domain \%domain, qw(org perl www); insert_domain \%domain, qw(org perl use); insert_domain \%domain, qw(org perl jobs); insert_domain \%domain, qw(com perl www); insert_domain \%domain, qw(org cpan www); use Data::Dumper; print Dumper \%domain; __END__ $VAR1 = { 'org' => { 'cpan' => { 'www' => {} }, 'perl' => { 'www' => {}, 'jobs' => {}, 'use' => {} }, 'perlmonks' => { 'www' => {} } }, 'com' => { 'perl' => { 'www' => {} }, 'perlmonks' => { 'www' => {} } } };
Makeshifts last the longest.
In reply to Re: storing domain info in hashes of hashes
by Aristotle
in thread storing domain info in hashes of hashes
by ajefferies
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |