in reply to Assign a value to a hash of unknown nodes

#!/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 );
An example usage:
> ./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.

Replies are listed 'Best First'.
Re^2: Assign a value to a hash of unknown nodes
by jigglermwm (Initiate) on Jul 13, 2011 at 17:22 UTC
    thanks for the example, I'll give it a go