in reply to A hash slice but not..
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: A hash slice but not..
by extremely (Priest) on Feb 15, 2001 at 00:48 UTC | |
by tilly (Archbishop) on Feb 15, 2001 at 00:53 UTC | |
by extremely (Priest) on Feb 15, 2001 at 01:05 UTC | |
by chipmunk (Parson) on Feb 15, 2001 at 00:59 UTC | |
|
Re: Re: A hash slice but not..
by smferris (Beadle) on Feb 15, 2001 at 01:32 UTC |