kaye
kaye

Reputation: 47

Declare hash variable in loop

I need to use a hash and loop in my code. Please see the sample code it's not working. i wanted to print the variable wafer, site and res side by side so it will look like this

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";

Upvotes: 0

Views: 88

Answers (1)

choroba
choroba

Reputation: 241988

When you want to iterate several arrays synchronously, iterate over the indices:

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

You also might want to build a hash keyed by the site (as it's the only unique value):

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

This will create a hash like this:

%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'
             }
    );

Upvotes: 5

Related Questions