An example usage:#!/usr/bin/perl use Data::Dumper; use warnings; use strict; die("usage: $0 <key>=<value> [<key>=<value> ...]\n") unless @ARGV; my %hash; foreach my $set (@ARGV) { my($keys, $value) = split /=/, $set, 2; my @keys = split /\//, $keys; my $lastkey = pop @keys; my $h = \%hash; foreach my $key (@keys) { if (ref $h->{$key} eq 'HASH') { $h = $h->{$key} } else { $h = $h->{$key} = {} } } $h->{$lastkey} = $value; } print( Data::Dumper ->new ([\%hash]) ->Useqq (1) ->Terse (1) ->Indent(1) ->Dump );
> ./create-nested-hash.pl foo/bar/baz=10 spam/eggs/ham=hi foo/stuff=20 + top='Tophat!' { "spam" => { "eggs" => { "ham" => "hi" } }, "top" => "Tophat!", "foo" => { "bar" => { "baz" => 10 }, "stuff" => 20 } }
While this sort of thing is fun to write, be careful you don't create an unreadable mess. Data-driven programs are an excellent idea; data-driven data structures have a tendency to become unmanageable. The problem is it's far less understandable what the data structure looks like after you go through a few transformations.
In reply to Re: Assign a value to a hash of unknown nodes
by Somni
in thread Assign a value to a hash of unknown nodes
by jigglermwm
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |