在Perl中递归转换嵌套哈希表

时间:2013-03-27 05:52:45

标签: json perl recursion

我有一个嵌套的哈希表,如下所示:

{"a": {"b": {"c": {"d": "", "e": ""},
             "m": ""},
       "f": ""},
 "h": {"i": {"j": "", "k": ""}
      }
}

我想把它转换成这样的格式:

[
    {"title": "a", "isFolder": true,
        "children": [
            {"title": "b", "isFolder": true",
                "children": [
                    {"title": "c", "isFolder": true",
                        "children": [
                            {"title": "d"},
                            {"title": "e"}
                        ]
                    },
                    {"title": "m"}
                ]
            },
            {"title": "f"},
            {"title": "g"}
        ]
    },
    {"title": "h", "isFolder": "true",
        "children": [
            {"title": "i", "isFolder": "true",
                "children": [
                    {"title": "j"},
                    {"title": "k"}
                ]
            }
        ]
    }
]

所以我写了一个程序:

#!/usr/bin/perl

use JSON;

$json = JSON->new->allow_nonref;

$struct = [];
sub convertRaw() {
    ($raw, $ts) = @_;

    foreach (keys %$raw) {
        if ($raw->{$_}) {
            push @$ts, {"title" => $_, "isFolder" => "true", "children" => []};
            &convertRaw($raw->{$_}, @$ts[-1]->{"children"});
        }
        else {
            push @$ts, {"title" => $_};
        }
    }
}

$raw_struct = {"a"=> {"b"=> {"c"=> {"d"=> "", "e"=> ""},
                             "m"=> ""},
                      "f"=> ""},
               "h"=> {"i"=> {"j"=> "", "k"=> ""}
                     }
              };

&convertRaw($raw_struct, $struct);

print $json->pretty->encode($struct)."\n";

然而,输出结果是这样的:

[
   {
      "isFolder" : "true",
      "children" : [
         {
            "isFolder" : "true",
            "children" : [
               {
                  "title" : "k"
               },
               {
                  "title" : "j"
               },
               {
                  "title" : "a"
               }
            ],
            "title" : "i"
         }
      ],
      "title" : "h"
   }
]

真的很困惑。你能弄明白这里有什么问题吗?

1 个答案:

答案 0 :(得分:1)

您已全局声明变量$raw$ts。因此,子元素处理期间的哈希更新将影响父元素的未来处理。 Declare them as lexically scoped variables

sub convertRaw {
    my ($raw, $ts) = @_;
    # the rest of the code