Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Having an Issue updating hash of hashes

by 2teez (Vicar)
on Jul 05, 2014 at 17:12 UTC ( [id://1092380]=note: print w/replies, xml ) Need Help??


in reply to Having an Issue updating hash of hashes

hi perlguyjoe,
Seems I am overwriting my hash, instead of adding a new hash

Am afraid to say you are right. Something like this could show some light, I suppose!
use warnings; use strict; use Data::Dumper; my %person; my $key; while (<DATA>) { for ( split /\s+/, $_ ) { if (/^(ID)=(.)/) { $key = $2; $person{$key} = { lc $1 => $2 }; } else { my ( $new_key, $value ) = split /=/, $_; $person{$key}{ lc $new_key } = $value; } } } print Dumper \%person; __DATA__ ID=1 First=John Last=Doe AGE=42 ID=2 First=Jane Last=Doe AGE=35 ID=3 First=Jack Last=Doe AGE=17 ID=4 First=Jill Last=Doe AGE=15
And if I may add see this also perldsc

Update
In fact, you can remove all the drama of if/else within the for loop and do:
$key = $1 if /^ID=(.)/; my ( $new_key, $value ) = split /=/, $_; $person{$key}{ lc $new_key } = $value;
If you tell me, I'll forget.
If you show me, I'll remember.
if you involve me, I'll understand.
--- Author unknown to me

Replies are listed 'Best First'.
Re^2: Having an Issue updating hash of hashes
by AppleFritter (Vicar) on Jul 05, 2014 at 18:42 UTC

    This bit will stop working once you start getting multi-digit IDs:

    $key = $1 if /^ID=(.)/;

    You'll want this instead:

    $key = $1 if /^ID=([^\s]+)/;

    Otherwise you'll end up silently overwriting previous entries.

      This bit will stop working once you start getting multi-digit IDs:

      $key = $1 if /^ID=(.)/;
      Obviously, BUT the OP data set doesn't say otherwise and I don't intend to think for the OP!
      Am only using the OP dataset provided with that the line suffices!

      Update:

      You'll want this instead:

      $key = $1 if /^ID=([^\s]+)/;
      Otherwise you'll end up silently overwriting previous entries.

      And what happens if the OP has two or ID with the same value, even with the code above?! Oops!!
      Maybe the OP first intention of using a counter will do for all intent and purpose!

      If you tell me, I'll forget.
      If you show me, I'll remember.
      if you involve me, I'll understand.
      --- Author unknown to me

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (3)
As of 2024-03-29 07:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found