in reply to can i rename hashref keys?

Actually hash keys are read only (that's the point: you can only successfully build a hash table if the hash function always returns the same value).

But you can delete pairs, and add them with a different key:

my %name_changes = ( mm => 'month', yyyy => 'year', ); for (keys %name_change){ $h->{$name_change{$_}} = $h->{$_}; delete $h->{$_}; }

You have to decide for yourself if that's worth the effort, or if you just want to rebuild the hash anew.

Replies are listed 'Best First'.
Re^2: can i rename hashref keys?
by dave_the_m (Monsignor) on Nov 29, 2007 at 17:09 UTC
    Given that delete returns the deleted value, this can be simplified:
    my %map = (....); $h->{$map{$_}} = delete $h->{$_} for keys %map;

    Dave.

      Given that delete can delete a slice, this can be simplified:

      my %map = (...); @$h{values %map} = delete @$h{keys %map};

      Update: note that this doesn't break on %map = (foo => 'bar', bar => 'foo') that the solutions above may do.

      lodin

        Given that initializing the hash just requires you list a bunch of keys and values, this can be simplified:

        @{$h}{qw/ month year day first_name /}= delete # New keys @{$h}{qw/ mm yyyy dd name /}; # Old keys

        Yeah, I added some extra braces.

        - tye        

      and even more concisely, using a hash slice:

      @{$h}{qw{month year day first_name}} = delete @{$h}{qw{mm yyyy dd name +}}; C:\@Work\Perl>perl -wMstrict -e "my $h = { mm => 'July', yyyy => '1975', dd => '31', name => 'Milo', l +ast_name => 'Manara',}; print qq(o/p: \n); print qq($_ => $h->{$_} \n) for keys %$h; @{$h}{qw{month year day first_name}} = delete @{$h}{qw{mm yyyy dd name +}}; print qq(-----\n); print qq($_ => $h->{$_} \n) for keys %$h" o/p: mm => July name => Milo dd => 31 last_name => Manara yyyy => 1975 ----- month => July day => 31 first_name => Milo year => 1975 last_name => Manara