2017-04-06 2 views
0

je le tableau suivant ...Hash itératives Configurer

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

De ce tableau, je veux construire itérativement un hachage.

Script actuel:

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

Courant de sortie:

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

Ce n'est pas ce que je veux. Mon but est ...

Objectif Sortie:

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

Que dois-je faire?

J'utilise: Perl 5, version 18

Répondre

1

Attribution à un hachage quelque chose — que vous faites chaque passage de la boucle — remplace son contenu. Remplacer

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

avec

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

Sinon, tout remplacer par

my %hash = map { split } @array; 
+0

je l'option Sinon, il fonctionne parfaitement! @ikegami –