in reply to How do I populate a ML hash from an array?
Here's an updated form of my code example from that discussion:
This subroutine can be used to set and get the value. If there's a third argument to the subroutine, it's set as the new value for the keys; either way the value for the keys is returned.use strict; sub nested_value { my $href = shift; my $keys = shift; my $last_key = pop @$keys; for my $key (@$keys) { $href = $href->{$key} ||= {}; } if (@_) { $href->{$last_key} = shift; } return $href->{$last_key}; } my %hash; nested_value(\%hash, [qw/one two three/], 1); print nested_value(\%hash, [qw/one two three/]), "\n"; use Data::Dumper; print Dumper \%hash;
Note that this code assumes that each key will either point to a hash reference or to a value. If you set a value first, and then try to use it as a nested hash, you'll get an error from use strict. If you set a nested hash first, and then set a value at the same level, you'll delete the entire nested hash. Error checking could be added to the sub to handle those situations gracefully.
|
|---|