【发布时间】:2014-05-18 15:17:26
【问题描述】:
我在将数组中的哈希引用到另一个数组时遇到问题。 我有一个数组@result,如下所示:
@result = (
{ "type" => "variable",
"s" => "NGDP",
"variable" => "NGDP" },
{"type" => "subject",
"s" => "USA",
"subject" => "USA",
"variable" => "NGDP" },
{ "type" => "colon",
"s" => ",",
"colon" => "," },
{ "type" => "subject",
"s" => "JPN",
"subject" => "JPN",
"variable" => "NGDP" },
{ "type" => "operator",
"s" => "+",
"operator => "+" },
{"type" => "subject",
"s" => "CHN",
"subject" => "CHN",
"variable" => "NGDP" },
);
我想把这个数组分成冒号,并将@result数组的元素推送到另一个数组,所以我写了脚本:
for ($i = 0; $i <= $#result; $i++) {
if (defined $result[$i]{subject} or $result[$i]{operator} and not defined $result[$i]{colon}) {
push @part_col, \%{$result[$i]};
}
elsif ($i == $#result) {
push @part_col_all, \@part_col;
}
elsif (defined $result[$i]{colon}) {
push @part_col_all, \@part_col;
my @part_col;
}
}
所以我需要的是,如果我打印出$part_col_all[0][0]{subject},结果将是"USA",
对于$part_col_all[1][0]{subject} 将是"JPN",
对于$part_col_all[1][1]{operator} 将是"+" 等等。
我对@987654329@ 的结果是"USA"
对于$part_col_all[0][1]{subject} 是"JPN",它应该在$part_col_all[1][0]{subject}。
$part_col_all[0][3]{subject} 的结果是 "CHN",而它应该在 $part_col_all[1][2]{subject} 中。
我正在制作一个应用程序,该应用程序根据特定的经济输入从经济数据创建图表。 @result 数组是我的预处理输入,我知道哪个变量属于哪个国家/地区。如果我得到像 GDP USA CAN、JPN+CHN 这样的输入,我需要将此输入拆分为 GDP USA CAN 和 JPN+CHN。这就是为什么我做了一个条件,如果找到冒号,将@part_col 中的所有内容推送到@part_col_all 的第一个元素,然后如果它在输入的末尾,则将JPN+CHN 推送到@push_col_all 的第二个元素。
所以@part_col_all 应该是这样的:
@part_col_all = (
(
{"type" => "subject",
"s" => "USA",
"subject" => "USA",
"variable" => "NGDP" },
{"type" => "subject",
"s" => "CAN",
"subject" => "CAN",
"variable" => "NGDP" },
),
(
{ "type" => "subject",
"s" => "JPN",
"subject" => "JPN",
"variable" => "NGDP" },
{ "type" => "operator",
"s" => "+",
"operator" => "+" },
{"type" => "subject",
"s" => "CHN",
"subject" => "CHN",
"variable" => "NGDP" },
)
);
我不知道我做错了什么。很抱歉,如果有任何基本错误,我是初学者。非常感谢。
【问题讨论】:
标签: arrays perl hash reference