in reply to Re: read flat file and build tree-like structure
in thread read flat file and build tree-like structure

Close. Keep track of a reference to the reference.

my %hash; while (<>) { chomp; my ($key, $val) = split(/=/, $_, 2); my @elts = split(/\./, $key); my $p = \\%hash; $p = \( ${$p}->{$_} ) for @elts; $$p = $val; } use Data::Dumper; print Dumper(\%hash);

Tested.

Replies are listed 'Best First'.
Re^3: read flat file and build tree-like structure
by manav_gupta (Acolyte) on Nov 19, 2007 at 17:17 UTC
    Wow, that's awesome. I'd been wondering for last few hours on the best way of doing it... thank you so much!
      Couple of follow-up questions: 1. Could you please explain what the following snippet does?
      my $p = \\%hash; $p = \(${$p}->{$_}) for @elts; $$p = $val;
      2. Is there a quick/easy way to change the key of a hash? Apologies if I'm breaking a rule here (double/cross-posting)...

        There's no problem with asking follow up questions.

        1. Just like

        DiveVal(\%hash, map \$_, @elts) = $val;

        it does

        $hash{ $elts[0] }{ $elts[1] }...{ $elts[n-1] } = $val;

        If you have data like

        foo.bar=val foo.bar.baz=val

        you'd be better off with pc88mxer's updated code.

        2. Keys can be added and removed, not changed. However, combining a removal and an addition is easy.

        $hash{$new_key} = delete $hash{$old_key};

        or

        $hash{$new_key} = delete $hash{$old_key} if exists $hash{$old_key};