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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.