in reply to Re: How can I delete a key' value from a hash
in thread How can I delete a key' value from a hash

Oh, good catch. I should not be deleting both inside of the inner loop! Thanks! I am trying to remove the values after processing because, I can possibly receive an error from this program and I need to know which cities I processed when the error occurred. So, I wont process the same cities again.
It appears that it will delete the zip code and state but not the city.
printf "Before deleting: city= %s state=%s zip= %s\n", $city , $location_hash->{ $city }->{ 'ST' }, $location_hash->{ $city }->{ 'ZIP' }; delete ($location_hash->{ $city }); delete ($location_hash->{ $city }->{ 'ST' }) ; delete ($location_hash->{ $city }->{ 'ZIP' }) ; printf "After deleting: city= %s state=%s zip= %s\n", $city, $location_hash->{ $city }->{ 'ST' }, $location_hash->{ $city }->{ 'ZIP' };

Output:

Before deleting: city= Lucketts state=VA zip= 20176 After deleting: city= Lucketts state= zip=
Ok, I feel like an idiot ... lol It kept printing $city because it was NOT in the hash. $city was declared above. I almost did not admit it but I wanted you all to get a good laugh :) new code:
for my $city ( keys %$location_hash ) { . . . printf "Before deleting: state=%s zip= %s\n", $location_hash->{ $city }->{ 'ST' }, $location_hash->{ $city }->{ 'ZIP' }; delete ($location_hash->{ $city }); ### delete ($location_hash->{ $city }->{ 'ST' }) ; ### delete ($location_hash->{ $city }->{ 'ZIP' }) ; printf "After deleting: state=%s zip= %s\n", $location_hash->{ $city }->{ 'ST' }, $location_hash->{ $city }->{ 'ZIP' }; } end for loop
Output:
Before deleting: state=VA zip= 20176 After deleting: state= zip= Before deleting: state=VA zip= 20176 After deleting: state= zip=
Everyone, thanks for your help. Sometimes it helps to have someone to talk to about it and as you explain it you think, "Dah."

Replies are listed 'Best First'.
Re^3: How can I delete a key' value from a hash
by Animator (Hermit) on Jan 08, 2007 at 12:16 UTC

    Just for your information:

    printf "After deleting: state=%s zip= %s\n", $location_hash->{ $city }->{ 'ST' }, $location_hash->{ $city }->{ 'ZIP' };

    This code will re-create the key $city} in %$location_hash. $location_hash->{$city} has to exists before it can look up ST and/or ZIP. (autovivication)

    Another note: $location_hash->{$city}->{'ST'} is the same as: $location_hash->{$city}{'ST'} which is the same as: <code>$location_hash->{$city}{ST}