Let us say if I have a hash like this:
$data = {
'key1' => {
'key2' => 'value1'
},
'key3' => {
'key4' => {
'key5' => 'value2'
}
},
};
Now, how can I replace the the key 'key5' with some other key name, say 'key6'?
I know how to loop through the hash and dump the values, but I don't know how to replace keys or values in place.
Perl for Beginners: Learn A to Z of Perl Scripting Hands-on Hash variables are preceded by a percent (%) sign. To refer to a single element of a hash, you will use the hash variable name preceded by a "$" sign and followed by the "key" associated with the value in curly brackets..
Basic Perl hash "add element" syntax$hash{key} = value; As a concrete example, here is how I add one element (one key/value pair) to a Perl hash named %prices : $prices{'pizza'} = 12.00; In that example, my hash is named %prices , the key I'm adding is the string pizza , and the value I'm adding is 12.00 .
Loop over Perl hash values Perl allows to Loop over its Hash values. It means the hash is iterative type and one can iterate over its keys and values using 'for' loop and 'while' loop. In Perl, hash data structure is provided by the keys() function similar to the one present in Python programming language.
For this, you use -> and either [] to tell Perl you want to access a list element, or {} to tell Perl you want to access a hash element: $scalar = $ref->[ 1 ]; $scalar = $ref->{ name1 }; NOTICE: you're accessing one element, so you use the $ sign.
The delete
operator returns the value being deleted. So this
$data->{key3}{key4}{key6} = delete $data->{key3}{key4}{key5}
will do what you're looking for.
You can't replace it, but you can make a new key easily, and then delete()
the old one:
$data->{key3}{key4}{key6} = $data->{key3}{key4}{key5};
delete $data->{key3}{key4}{key5};
Of course, you could make a fairly simple subroutine to do this. However, my first approach was wrong, and you would need to make a more complex approach that passes in the data structure to modify and the element to be modified, and given that you want elements several levels deep this may be difficult. Though if you don't mind a little clutter:
sub hash_replace (\%$$) {
$_[0]->{$_[2]} = delete $_[0]->{$_[1]}; # thanks mobrule!
}
Then call it:
hash_replace %{$data->{key3}{key4}}, "key5", "key6";
Or the cool way (How better to say that we're transforming "key5" into "key6" ?):
hash_replace %{$data->{key3}{key4}}, key5 => "key6";
(Tested and works)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With