If you're looking to do this with an arbitrary list, here's a subroutine that shows one way to do it:
The for loop descends through the nested hashes. With the ||= operator, when there isn't already a hash reference at that level, it creates a new anonymous hash. $href is then reassigned to the next level in the nested hash.#!/usr/local/bin/perl -w use strict; sub set_nested_value { my($href, $keys, $value) = @_; my $last_key = pop @$keys; for my $key (@$keys) { $href = $href->{$key} ||= {}; } $href->{$last_key} = $value; } my %hash; set_nested_value(\%hash, ['a' .. 'c'], 'some value'); set_nested_value(\%hash, ['a', 'b', 'd'], 'other value'); 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.
In reply to Re: A hash slice but not..
by chipmunk
in thread A hash slice but not..
by smferris
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |