1

我正在遍历 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数组中,然后在节点属性中打印它。

我的 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;
        }
    }
}

任何帮助表示赞赏。

4

1 回答 1

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;
 }
}
于 2013-09-27T18:25:24.340 回答