perl add to hash
To add an element to a hash in Perl, you can use the assignment operator (=>
) to assign a value to a specific key in the hash. Here's an example:
my %hash = (
key1 => 'value1',
key2 => 'value2',
);
$hash{key3} = 'value3'; # Adding a new key-value pair to the hash
print %hash; # Output: key1value1key2value2key3value3
In the example above, we first initialize a hash %hash
with two key-value pairs. Then, we add a new key-value pair (key3
and value3
) to the hash using the assignment operator (=
). Finally, we print the hash, which will display all the key-value pairs.
Please note that the order of the key-value pairs may vary when printing the hash, as hashes in Perl do not preserve the order of insertion.
I hope this helps! Let me know if you have any further questions.