in reply to Populating a nested hash with itself?

I did notice that Data::Dumper does nearly the same thing you're trying to do ... and I'm trying to figure out how to get Data::Dumper's output to "thaw" back into a usable perl variable. Perhaps someone else will answer this.

my $a = [qw{v1 v2}]; my %h = ( k1 => { k11 => $a, k12 => 'w00t!', }, k2 => { k21 => 'what?', k22 => $a, }, ); use Data::Dumper; #print Dumper(\%h); my $h2; $h2 = { 'k2' => { 'k21' => 'what?', 'k22' => [ 'v1', 'v2' ] }, 'k1' => { 'k11' => $h2->{'k2'}{'k22'}, 'k12' => 'w00t!' } }; print Dumper($h2);
The first hash, %h, is what you're trying to do, but in a manner that works. Then I dump it, and I pasted that output back into the code and dump the new hash-ref, $h2. But it doesn't want to work, and I'm not sure what bits of trickery are needed to get it to work - probably some Data::Dumper variables when dumping, but I'm not sure offhand.

Replies are listed 'Best First'.
Re^2: Populating a nested hash with itself?
by halley (Prior) on Jul 06, 2005 at 18:14 UTC
    The output of Data::Dumper is not guaranteed to properly evaluate and reconstruct the data, unless you set $Data::Dumper::Purity = 1. It is still possible to confuse Data::Dumper in some cases, but with Purity, it'll handle most self-referential and other cyclical structures. The output with this configuration:
    $VAR1 = { 'k1' => { 'k11' => [ 'v1', 'v2' ], 'k12' => 'w00t!' }, 'k2' => { 'k21' => 'what?', 'k22' => [] } }; $VAR1->{'k2'}{'k22'} = $VAR1->{'k1'}{'k11'};
    As you can see, Data::Dumper now produces Perl code, and not merely a Perl-like syntax to describe the data.

    --
    [ e d @ h a l l e y . c c ]