我循环遍历XML节点并为每个相似的节点创建一个组,例如以下节点:
<node name="ps1_uat1" host="" port="20014" />
<node name="ps1_uat2" host="" port="20014" />
<node name="ps1_uat3" host="" port="20014" />
...将生成以下组:
<nodeGroup name="ps1" nodes="" />
那里的一切都很好,但是在使用下面的代码循环时,我在循环中迷失了它并打印出来:
<nodeGroup name="ps1" nodes="ps1_it," />
<nodeGroup name="ps1" nodes="ps1_it, ps1_uat1," />
<nodeGroup name="ps1" nodes="ps1_it, ps1_uat1, ps1_uat2," />
<nodeGroup name="ps1" nodes="ps1_it, ps1_uat1, ps1_uat2, ps1_uat3," />
我只想打印出最后一个,我正在尝试收集所有相似的节点,并将它们推入@nodes
数组,然后将其打印在nodes属性中。
我的Perl代码:
foreach my $group (@groups) {
my @nodes;
foreach my $node (@nodenames) {
chomp($group);
chomp($node);
if ($node =~ m/$group/) {
push (@nodes, "$node,");
my $groupxml = "\t<nodeGroup name=\"$group\" nodes=\"@nodes\" \/>\n";
print ODSERVERFILE $groupxml;
}
}
}
感谢任何帮助。
答案 0 :(得分:2)
我相信你需要从内部for循环中移出两行代码。试试这个:
foreach my $group (@groups) {
my @nodes;
foreach my $node (@nodenames) {
chomp($group);
chomp($node);
if ($node =~ m/$group/) {
push (@nodes, "$node,");
}
}
// These 2 lines go out
my $groupxml = "\t<nodeGroup name=\"$group\" nodes=\"@nodes\" \/>\n";
print ODSERVERFILE $groupxml;
}
}