#!/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.


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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.