My inclination is to do it manually. That is,
$h->{first_name} = $h->{name}; delete $h->{name};
It's clear what it's doing, and if you're trying to change 'foo' to 'bar' and 'baz' to 'foo', it's clear if you got them in the wrong order.
But lets say you have many many keys, and you don't want to have a huge block of those copy/delete pairs. You could do something like this:
my $h = { mm => 'July', yyyy => '1975', dd => '31', name => 'Milo', last_name => 'Manara', }; my %replacement_for = ( mm => 'month', yyyy => 'year', dd => 'day', name => 'first_name', ); my @array_from_hash = %$h; my $x = 0; for ( @array_from_hash ) { if ( $x++ % 2 == 0 && exists $replacement_for{$_} ) { $_ = $replacement_for{$_}; } } my $h2 = { @array_from_hash }; print Dumper $h; print Dumper $h2; __END__ $VAR1 = { 'mm' => 'July', 'name' => 'Milo', 'dd' => '31', 'last_name' => 'Manara', 'yyyy' => '1975' }; $VAR1 = { 'month' => 'July', 'day' => '31', 'year' => '1975', 'last_name' => 'Manara', 'first_name' => 'Milo' };
This avoids the problem you get if one of your replacements is one of your original keys. It also avoids accidentally creating a hash pair where there wasn't one before (e.g., if your replacement list contains an element that isn't in the original hash). Both of these are things that I think could happen if you use the type of solution given by moritz and dave_the_m (but I haven't confirmed that).
On the other hand, it's not exactly elegant.
In reply to Re: can i rename hashref keys?
by kyle
in thread can i rename hashref keys?
by leocharre
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |