gpt4 book ai didi

Javascript 到 Perl 数组/哈希转换

转载 作者:行者123 更新时间:2023-11-30 17:21:09 25 4
gpt4 key购买 nike

我有以下 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 中构建此哈希/数组?除了做 10 个不同的循环并以这种方式构建之外,我无法弄清楚。但我希望它在代码运行之前就在那里。

最佳答案

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

关于Javascript 到 Perl 数组/哈希转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25125255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com