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} = 1They 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 ) }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^3: setting hash keys by array
by Aristotle (Chancellor) on Sep 09, 2002 at 19:22 UTC | |
by blssu (Pilgrim) on Sep 09, 2002 at 21:03 UTC | |
by Aristotle (Chancellor) on Sep 10, 2002 at 08:57 UTC |
In Section
Seekers of Perl Wisdom