phemal has asked for the wisdom of the Perl Monks concerning the following question:

i am passing the "key" dynamically in foreach loop but at the end if i print key and values i get the last key and its value and not all. So my question is there any way wherein we can pass the "key" dynamically.
foreach my $id ($doc->getElementsByTagName('attack')){ %_attack = ($id => { 'severity' => '0' 'category' => '1' }, ); }
  • Comment on unable to store keys and values in hash when "keys" are passed at runtime
  • Download Code

Replies are listed 'Best First'.
Re: unable to store keys and values in hash when "keys" are passed at runtime
by davorg (Chancellor) on Feb 15, 2007 at 10:51 UTC

    You are overwriting the hash each time round the loop. This removes all data in the hash and replaces it with the new values.

    It sounds like you want to add data to the hash on each iteration. In that case you just need to assign to the individual key.

    foreach my $id ($doc->getElementsByTagName('attack')) { $_attack{$id} = { 'severity' => '0', 'category' => '1', }; }
Re: unable to store keys and values in hash when "keys" are passed at runtime
by dorward (Curate) on Feb 15, 2007 at 10:53 UTC
    You're assigning a new list to the hash each time and overwriting whatever is there before.
    my %_attack; foreach (...) { $attack{$id} = ...; }