Iterative Hash Set up

I have the following array...

my @array=("100  2", "300  1", "200  3");

From this array I want to iteratively construct a hash.

Current Script:

my %hash; 
foreach (@array) {
 my @split = (split /\s+/, $_);
 %hash = ("$split[0]", "$split[1]");
} 

Current Output:

$VAR1 = {
         '200' => '3'
        };

This is not what I want. My goal is...

Goal Output:

$VAR1 = {
         '100' => '2'
         '300' => '1'
         '200' => '3'
        };

What do I need to do?

I am using: Perl 5, Version 18

Upvotes: 0

Views: 22

Answers (1)

ikegami
ikegami

Reputation: 385506

Assigning to a hash—something you are doing each pass of the loop—replaces its contents. Replace

%hash = ("$split[0]", "$split[1]");

with

$hash{$split[0]} = $split[1];

Alternatively, replace everything with

my %hash = map { split } @array;

Upvotes: 1

Related Questions