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

What do you mean "does not work"? Didn't run it myself, but it looks ok, other than deleting the city at the end of the inner loop (instead of the outer loop), when you presumably aren't quite done with it, and not having the categories available anymore when you process the second city.

Maybe you'd better explain why you want to delete them?

  • Comment on Re: How can I delete a key' value from a hash

Replies are listed 'Best First'.
Re^2: How can I delete a key' value from a hash
by kevyt (Scribe) on Jan 07, 2007 at 23:46 UTC
    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."

      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}