in reply to How can one change the keys of a hash to an alternative set of keys?

Use map. You might need to clone the hash if you don't want the input and output to share the inner structures.
#! /usr/bin/perl use strict; use warnings; use Clone qw{ clone }; use Test::More tests => 2; my $input_hash_ref = { key1 => { some_field => 'value1', key => 'key1', alt_key => 'alt_key1' }, key2 => { some_field => 'value2', key => 'key2', alt_key => 'alt_key2' } }; my $expected_hash_ref={ alt_key1 => { some_field => 'value1', key => 'key1', alt_key => 'alt_key1' }, alt_key2 => { some_field => 'value2', key => 'key2', alt_key => 'alt_key2' }, }; my $output_hash_ref = { map { $input_hash_ref->{$_}{alt_key} => $input +_hash_ref->{$_} } keys %$input_hash_ref }; is_deeply($output_hash_ref, $expected_hash_ref, 'same inner hashes'); my $clone = clone($input_hash_ref); my $cloned_hash_ref = { map { $clone->{$_}{alt_key} => $clone->{$_} } keys %$clone }; is_deeply($cloned_hash_ref, $expected_hash_ref, 'cloned');
لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
  • Comment on Re: How can one change the keys of a hash to an alternative set of keys?
  • Download Code

Replies are listed 'Best First'.
Re^2: How can one change the keys of a hash to an alternative set of keys?
by tkguifan (Scribe) on Feb 05, 2015 at 04:46 UTC
    This is an interesting response, because I also had problems with cloning my object. Currently I'm copying every field in the object by hand to the new object.
    sub clone { my $self=shift; my $clone=new Board; $clone->{rep}=$self->{rep}; $clone->{castling_rights}=$self->{castling_rights}; $clone->{half_move_clock}=$self->{half_move_clock}; $clone->{full_move_number}=$self->{full_move_number}; $clone->{ep_pos}=$self->{ep_pos}; $clone->{turn}=$self->{turn}; return $clone; }
      ... copying every field in the object by hand to the new object.

      Maybe (untested):

      use Scalar::Util qw(blessed); sub clone { my $self = shift; my $clone = blessed($self)->new or die "clone failed ($self)"; @{$clone}{keys %$self} = (values %$self); return $clone; }
      Of course, this is still essentially "copying by hand" with lotsa potential pitfalls.


      Give a man a fish:  <%-(-(-(-<

      It works only for the listed keys, and also, it only works if the hash is not deeper (no reference to a hash, array, or whatever).
      لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ