jigglermwm has asked for the wisdom of the Perl Monks concerning the following question:

Hello This seems like it should be easy, but I haven't found a nice solution yet. What is happening Basically I am receiving input where each line has an unknown number of elements separated by "/". example input line a/b/c/d/e Each input line will result in a new hash like $hash{$a}{$b}{... = value Not sure how to properly create the hash when I have an unknown number of elements per line I could put @fields through a foreach loop, but that seems like a lot of redundant hash keys created and wasted cpu cycles to get to the finial key/value assignment

while (<>) { chomp; @fields = split /\//, $_;

Replies are listed 'Best First'.
Re: Assign a value to a hash of unknown nodes
by Somni (Friar) on Jul 13, 2011 at 17:13 UTC
    #!/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.

      thanks for the example, I'll give it a go
Re: Assign a value to a hash of unknown nodes
by AnomalousMonk (Archbishop) on Jul 13, 2011 at 18:56 UTC

    Quick and dirty. (Well, dirty anyway.)

    >perl -wMstrict -le "use Data::Dumper; ;; my @lines = qw(a/b/c/d/e a/b/c/f a/g x/y); my %hash; for my $line (@lines) { eval qq{\$hash{ @{[ join '}{', split qr{/}xms, $line ]} } = 1;}; } print Dumper \%hash; " $VAR1 = { 'a' => { 'g' => 1, 'b' => { 'c' => { 'd' => { 'e' => 1 }, 'f' => 1 } } }, 'x' => { 'y' => 1 } };
Re: Assign a value to a hash of unknown nodes
by Anonymous Monk on Jul 13, 2011 at 16:51 UTC
      thanks I'll take a look
Re: Assign a value to a hash of unknown nodes
by metaperl (Curate) on Jul 13, 2011 at 21:12 UTC