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

Dear monks, I have a HoH called %lists that looks like:

$VAR1 = { 'outdoor' => { 'cat' => 'other', 'desc' => 'Outdoor activities' }, 'Testlist' => { 'cat' => 'other', 'desc' => '' }, }
I supposed that to modify the list (the hash's key), this should work:
for my $list ( keys %lists ) { $lists{$list}{desc} = check_desc $lists{$list}{desc}; $list = "[mailto:$list\@example.com $list]"; }
The desc changes ok, but the list doesn't change. Why is that?

Well done is better than well said. -- Benjamin Franklin

Replies are listed 'Best First'.
Re: Modifying hash keys via the control variable
by choroba (Cardinal) on Dec 16, 2013 at 14:06 UTC
    keys returns a list of strings, not aliases to the real hash keys. Imagine an array instead of a hash - would you expect the following to work?
    # Simulate shift. (Does NOT work!) for my $i (1 .. $#array) { $i--; }

    To "change" a hash key, you have to delete it and create a new one:

    $hash{newkey} = delete $hash{oldkey};
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: Modifying hash keys via the control variable
by LanX (Saint) on Dec 16, 2013 at 14:05 UTC
    Hash keys are immutable!

    You could delete the old one and create a new one.

    In your case better a complete new hash.

    But I'd rather add a new subkey email!

    Your data model attracts problems...

    Cheers Rolf

    ( addicted to the Perl Programming Language)

Re: Modifying hash keys via the control variable
by NetWallah (Canon) on Dec 16, 2013 at 15:03 UTC
    You are better off creating a new hash, since both keys and values are being modified.
    my %newhash = map { my $list=$_; "\[mailto:$list\@example.com $list]" => { map { $_ => $_ eq 'desc' ? check_desc $lists{$ +list}{desc} : $lists{$list}{$_} } keys %{$lists{$list} } keys %lists;
    Notes:
    1 ) Untested
    2) This is a Shallow copy of the inner hash.
    3) '$list' is a confusing name for the key

                 When in doubt, mumble; when in trouble, delegate; when in charge, ponder. -- James H. Boren