在循环中声明哈希变量

kay*_*ato 0 perl

我需要在代码中使用哈希和循环。请查看示例代码,它不起作用。我想并排打印可变晶片,站点和资源,所以看起来像这样

1, 1, 63 
1, 2, -53 
1, 3, 9.47 
1, 4, 9.55 
1, 5, -8.32

my @wafer = ("1","1","1","1","1");
my @site = ("1", "2", "3", "4", "5");
my @res = ("63","-53","9.47","9.55","-8.32");

my %hash;
foreach my $result(@res) {
    $hash{$wafer[0]}{$site[0]} = $result;
    last;
}

print "$wafer{$wafer[0]}{$site[0]} \n";
Run Code Online (Sandbox Code Playgroud)

cho*_*oba 5

当您要同步迭代多个数组时,请遍历索引:

for my $index (0 .. $#wafer) {
    print "$wafer[$index] $site[$index] $res[$index]\n";
}
Run Code Online (Sandbox Code Playgroud)

您可能还想构建一个以网站为键的哈希(因为它是唯一的唯一值):

for my $index (0 .. $#wafer) {
    $hash{ $site[$index] } = { wafer => $wafer[$index],
                               res   => $res[$index] };
}
Run Code Online (Sandbox Code Playgroud)

这将创建一个像这样的哈希:

%hash = (
      '4' => {
               'res' => '9.55',
               'wafer' => '1'
             },
      '3' => {
               'wafer' => '1',
               'res' => '9.47'
             },
      '1' => {
               'res' => '63',
               'wafer' => '1'
             },
      '2' => {
               'res' => '-53',
               'wafer' => '1'
             },
      '5' => {
               'res' => '-8.32',
               'wafer' => '1'
             }
    );
Run Code Online (Sandbox Code Playgroud)