【问题标题】:Convert nested hash table recursively in Perl在 Perl 中递归转换嵌套哈希表
【发布时间】:2013-03-27 16:21:44
【问题描述】:

我有一个嵌套的哈希表,像这样:

{"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"
   }
]

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

【问题讨论】:

    标签: json perl recursion


    【解决方案1】:

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

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

    【讨论】:

    • 这就是问题所在!我最好添加use strict; 以避免这种情况...非常感谢。
    • @duskast 是的,use strict; 不会允许这种情况发生
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-19
    • 2015-01-02
    • 2018-12-17
    • 1970-01-01
    • 2021-07-24
    相关资源
    最近更新 更多