Perl foreach循环困境

时间:2013-09-27 18:12:50

标签: xml perl loops foreach

我循环遍历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;
        }
    }
}

感谢任何帮助。

1 个答案:

答案 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;
 }
}