Perl:Foreach循环

时间:2015-12-17 07:24:37

标签: xml perl foreach

尝试使用这段代码从XML文件中提取信息,我没有按预期获得所需的输出,我知道它在foreach循环中的内容,      - >我的问题是如何在这种情况下使用foreach循环

 use strict;
 use XML::Simple;
 use Data::Dumper;

 my %top_in_ou_bi;
 $top_in_ou_bi{"input"}{name}=add;
 $top_in_ou_bi{"input"}{name}=clk;
 $top_in_ou_bi{"input"}{name}=dat_in;
 $top_in_ou_bi{"output"}{name}=dat_out;
 $top_in_ou_bi{"bidirection"}{name}=ctrl;

 foreach my $nam(sort keys %top_in_ou_bi){
        foreach my $dat(keys %{$top_in_ou_bi{$nam}}){
                print"$nam $dat: $top_in_ou_bi{$nam}{$dat}\n";
   }
 }

输出:

bidirection name: ctrl
input name: dat_in
output name: dat_out

预期产出:

bidirection name: ctrl
input name: dat_in
input name: clk
input name: add
output name: dat_out

也使用“use strict”警告不允许使用裸词,如何超越此警告!

谢谢!

修改

我想知道下面的代码段是否有效?

   my $top_in=$root_top->{input};
   my $top_ou=$root_top->{output};
   my $top_bi=$root_top->{bidirection};
   foreach my $name(keys %$top_in)
   {
     print "input $name\n";
    }
   foreach my $name(keys %$top_ou)
   {
     print "output $top_ou->{name}\n";
   }
   foreach my $name(keys %$top_bi)
   {
     print "bidirection $top_bi->{name}\n";
   }

2 个答案:

答案 0 :(得分:7)

它与foreach循环无关。问题是如何填充%top_in_ou_bi哈希。哈希只能包含每个键的单个值。在密钥"input"下存储多个值时,只剩下最后一个值。

你可以做的最好的事情是在每个键上存储一个数组(通过引用)而不是标量值。或者您可以使用Hash::MultiValue等模块。

要取消裸字警告,请勿使用裸字。引用事物('add'而不是add等)或声明变量(取决于你想要完成的事情)。

答案 1 :(得分:1)

如果您考虑数据的模式,您会理解inputoutputbidirectional可能包含一组属性列表。你还提到了

  

可以有多个"输入","输出"或"双向"

在Ted Hopp的回答评论中。这意味着你有这样的数据本质上是一个列表,并存储这样的数据,最好的结构是数组。一个非常基本的数据结构点。 Ted Hopp正确地指出了原始问题。但是,如果您不确定要编写正确的代码,则以下代码段可能会有所帮助

use strict;
use XML::Simple;
use Data::Dumper;

my %top_in_ou_bi = ('input' => [], 'output' => [], 'bidirectional' => []);
push @{$top_in_ou_bi{'input'}}, {name => 'add', 'new' => 'value'};
push @{$top_in_ou_bi{'input'}}, {name => 'clk'};
push @{$top_in_ou_bi{'input'}}, {name => 'dat_in'};
push @{$top_in_ou_bi{'output'}}, {name => 'dat_out'};
push @{$top_in_ou_bi{'bidirection'}}, {name => 'ctrl', 'something' => 'else'};

foreach my $type(sort keys %top_in_ou_bi){
    foreach my $properties (@{$top_in_ou_bi{$type}}){
        foreach my $key (keys %$properties){
            print "$type $key: $$properties{$key}\n";
        }
    }
}

输出:

bidirection name: ctrl
bidirection something: else
input name: add
input new: value
input name: clk
input name: dat_in
output name: dat_out