Dynamically/recursively building hashes in Perl?

前端 未结 5 1130
北恋
北恋 2020-12-19 04:45

I\'m quite new to Perl and I\'m trying to build a hash recursively and getting nowhere. I tried searching for tutorials to dynamically build hashes, but all I could find wer

5条回答
  •  攒了一身酷
    2020-12-19 05:05

    I ran your code and found a few problems:

    • you haven't scoped @elements properly.
    • with that recursion you're creating a hash that references itself, which is not what you want.
    • in your outermost call, the second arg to constructHash() is a string, but on the recursive call inside, you pass an array of @elements

    Try this.

    use Data::Dumper;
    
    my $finalhash = {}; 
    my @input = split "\n", < constructHash($remainder) } ; 
        } else {
            return { $first , "" }; 
        }
    }
    
    foreach $lines (@input) {
        my $linehash = constructHash($lines);
        my $firstkey = (keys %$linehash)[0];
    #    print Dumper $linehash;
        $finalhash->{$firstkey} = $linehash->{$firstkey};
    } 
    
    
    print Dumper $finalhash;
    

    It produces

    $VAR1 = {
              'five' => {
                          'six' => {
                                     'seven' => {
                                                  'eight' => ''
                                                }
                                   }
                        },
              'one' => {
                         'two' => {
                                    'three' => ''
                                  }
                       },
              'four' => ''
            };
    

    Remember, Perl hashes aren't ordered.

提交回复
热议问题