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

Hi monks I dont know this and have been searching for the solution. Can we rename a hash key without copying it to another key and deleting the first one. Tell me if there is any approach for this. Regards Sid

Replies are listed 'Best First'.
Re: Renaming a Hash key
by bart (Canon) on Apr 13, 2005 at 14:25 UTC
    No the closest you can get is
    $hash{$new} = delete $hash{$old};
Re: Renaming a Hash key
by inman (Curate) on Apr 13, 2005 at 14:36 UTC
    A hash key isn't just a name, it is used to calculate the location of the value. If you could change the name then you would effectively be copying and deleting.

    Why do you want to rename the key? Copying the value of a hash element into a new one isn't a problem. More complicated structures use a reference as the hash value. The referant stays where it is. This example is for a hash of lists.

    my %hash = (tom => ['sally', 'dave', 'jennie'], bertie => ['jean']); $hash{paul} = delete $hash{tom}; foreach (keys %hash) { print "$_ @{$hash{$_}}\n"; }
Re: Renaming a Hash key
by tlm (Prior) on Apr 13, 2005 at 14:25 UTC

    Think about it for a second: the hash key determines unambiguously the hash bucket where the value will be stored. This relationship is fixed. Different keys, almost always, point to different locations in storage; that's the whole idea behind hash tables.

    the lowliest monk

Re: Renaming a Hash key
by gellyfish (Monsignor) on Apr 13, 2005 at 14:19 UTC

    Not from Perl code no.

    /J\

Re: Renaming a Hash key
by rev_1318 (Chaplain) on Apr 13, 2005 at 14:22 UTC
    No, you cannot rename a hash key.

    Paul