Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

unable to store keys and values in hash when "keys" are passed at runtime

by phemal (Sexton)
on Feb 15, 2007 at 10:47 UTC ( [id://600176]=perlquestion: print w/replies, xml ) Need Help??

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} = ...; }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://600176]
Approved by marto
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (6)
As of 2024-04-25 22:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found