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

Gents Probably an obvious answer but i cant find it..... How do you substitue one key of a hash? Just the key! Its driving me crazy! I wont know what the key will be in advance so I need to interpolate......Wheeler

Replies are listed 'Best First'.
Re: Hash substitution
by suaveant (Parson) on Oct 09, 2008 at 12:41 UTC
    You can't change the key of a hash because the key decides how to find the data based on an algorithm.

    You must instead move the value, easiest done this way:

    $hash{newkey} = delete $hash{oldkey};
    The delete removes the value from the old hash location and returns the value, allowing you to put it in the new hash location.

                    - Ant
                    - Some of my best work - (1 2 3)

      use Data::Dumper; my %hash = ( apple => 'red', orange => 'orange', banana => 'yellow', ); my $old_key = 'orange'; my $new_key = 'carrot'; $hash{$new_key} = delete $hash{$old_key}; print Dumper(\%hash);
Re: Hash substitution
by GrandFather (Saint) on Oct 09, 2008 at 21:01 UTC

    It seems likely that is the wrong question and what you are trying to do is probably not a good way to be solving your problem. How about you describe the bigger problem and perhaps provide some sample code that runs and demonstrates the issue you have?


    Perl reduces RSI - it saves typing