http://www.perlmonks.org?node_id=196389


in reply to Re: setting hash keys by array
in thread setting hash keys by array

That code (and several other examples) don't work quite like the request:

$hash{red}{green}{brown} = 1

They do this instead:

$hash{red}{green}{brown} = { }

That inner-most key makes a lot of the foreach solutions kind of ugly because the last key must be treated specially -- unless there's a way to transmogrify a hash ref into a scalar ref? Here's a short reverse foreach that uses globs to solve the corner case:

my @array = qw(red green brown); use vars qw(%hash); foreach (reverse @array) { *hash = { $_ => (%hash) ? \%hash : 1 } }

The lexical version is more ugly and a lot less efficient:

my @array = qw(red green brown); my %hash; foreach (reverse @array) { %hash = ( $_ => (%hash) ? { %hash } : 1 ) }