Prefixing every key in a hash ref in Perl
I needed to prepend some text to every element in a Perl hash ref, so I came up with:
1 |
$hashref->{"prefix_$_"} = delete($hashref->{$_}) foreach (keys %$hashref); |
which prefixes each key of $hashref with "prefix_". After talking it over with Cliff, he was concerned with modifying the list in place while simultaneously iterating over it and suggested this solution:
1 |
%$hashref = map { +"prefix_$_" => $hashref->{$_} } keys %$hashref; |
One interesting thing about this solution is the requirement for a unary "+" in map in order to help Perl work out… continue reading.