Javascript到Perl数组/哈希转换

时间:2014-08-04 18:32:09

标签: javascript arrays perl hash

我在JavaScript中有以下代码:

    _pCombos = [
        [{row:9,col:0},{row:1,col:9},{row:1,col:2},{row:1,col:3},{row:1,col:4}],
        [{row:0,col:0},{row:0,col:1},{row:0,col:2},{row:0,col:3},{row:0,col:4}],
        [{row:2,col:0},{row:2,col:1},{row:2,col:2},{row:2,col:3},{row:2,col:4}],
        [{row:0,col:0},{row:1,col:1},{row:2,col:2},{row:1,col:3},{row:0,col:4}],
    ];

我会像这样访问它

    _pCombos[0][0].row (result = 9)
    _pCombos[0][1].col (result = 9)

如何在Perl中构建此Hash / Array?除了做10个不同的循环并以这种方式构建它之外,我无法弄明白。但我希望它能在代码运行之前就存在。

1 个答案:

答案 0 :(得分:2)

my $_pCombos = [
    [{row => 9,col => 0},{row => 1,col => 9},{row => 1,col => 2},{row => 1,col => 3},{row => 1,col => 4}],
    [{row => 0,col => 0},{row => 0,col => 1},{row => 0,col => 2},{row => 0,col => 3},{row => 0,col => 4}],
    [{row => 2,col => 0},{row => 2,col => 1},{row => 2,col => 2},{row => 2,col => 3},{row => 2,col => 4}],
    [{row => 0,col => 0},{row => 1,col => 1},{row => 2,col => 2},{row => 1,col => 3},{row => 0,col => 4}],
    ];

print $_pCombos->[0][0]{row}, "\n";
print $_pCombos->[0][1]{col}, "\n";

将打印

9
9

如果你想维护javascript语法,你可以使用json,如下所示:

use JSON::XS;

my $_pCombos_JSON_normalized = <<'END';
[
 [{"row":9,"col":0},{"row":1,"col":9},{"row":1,"col":2},{"row":1,"col":3},{"row":1,"col":4}],
 [{"row":0,"col":0},{"row":0,"col":1},{"row":0,"col":2},{"row":0,"col":3},{"row":0,"col":4}],
 [{"row":2,"col":0},{"row":2,"col":1},{"row":2,"col":2},{"row":2,"col":3},{"row":2,"col":4}],
 [{"row":0,"col":0},{"row":1,"col":1},{"row":2,"col":2},{"row":1,"col":3},{"row":0,"col":4}]
]
END

my $_pCombos = decode_json($_pCombos_JSON_normalized);

print $_pCombos->[0][0]{row}, "\n";
print $_pCombos->[0][1]{col}, "\n";

也会打印

9
9