in reply to How do I set up the recursion?

Your logic is faulty in the section which checks for 2 array elements. The problem is that you have two sections so that level of the tree happens to have 2 array elements(try print Dumper($tree)). So what happens is that your code logic enters the section name into the hash and set's it as the key with a value of undef:

if(scalar(@$aoa) == 2){ #<--------- chomp $aoa->[0]; $y=$aoa->[0]; # <-----grabs "Section1" $Config{$y}=undef; # <-------Assigns undef to it. return $key;

Hence your output. How to fix it. You will need to change your logic around. On top of that, your recursion should really pass around and return references. I've rewritten your code somewhat to traverse the tree correctly, (I made an assumption on what the resulting datastructure you wanted was):

Here's the new code:

sub deparse { my $aoa=shift; my %key; for $x (0..$#{$aoa}) { if(ref($aoa->[$x])) { %key=(%key, %{&deparse($aoa->[$x])}); } else { chomp $aoa->[0]; my $y=$aoa->[0]; if (ref($aoa->[1])) { my %C; $C{$y}=deparse($aoa->[1]); return \%C; } my %C; $C{$y}=$aoa->[1]; return \%C; } } return \%key; } __OUTPUT__ $VAR1 = { 'Section1' => { 'key2' => 'value2', 'key1' => 'value1', 'key3' => 'value3' }, 'Section2' => { 'key5' => 'value5', 'key6' => 'value6', 'key4' => 'value4' } };

HTH

Replies are listed 'Best First'.
Re: Re: How do I set up the recursion?
by sauoq (Abbot) on May 29, 2003 at 20:21 UTC
    (I made an assumption on what the resulting datastructure you wanted was)

    He pretty clearly wanted to keep the comments... I think he was going for something like this:

    { 'Section1' => { key1 => [ 'value1', 'Optional comment'] } }

    -sauoq
    "My two cents aren't worth a dime.";
    
Re: Re: How do I set up the recursion?
by pzbagel (Chaplain) on May 29, 2003 at 21:18 UTC

    Well, that is easy enough, just change one line in the code I posted:

    $C{$y}=$aoa->[1]; # to $C{$y}=[@$aoa[1..$#$aoa]]; __OUTPUT__ $VAR1 = { 'Section1' => { 'key2' => [ 'value2', ' #Comment2' ], 'key1' => [ 'value1' ], 'key3' => [ 'value3' ] }, 'Section2' => { 'key5' => [ 'value5' ], 'key6' => [ 'value6', ' ;Comment 6' ], 'key4' => [ 'value4' ] } };

    Thanks

Re: Re: How do I set up the recursion?
by TStanley (Canon) on May 29, 2003 at 23:57 UTC
    My original idea was to have the value as a scalar, only if it didn't have a comment with it. But upon reflection, it would be much easier on me to put it into an array by itself, for easier access.

    TStanley
    --------