Perl hash FAQ: How do I add an item/element to a Perl hash?
Answer: Adding an item to a Perl hash is just like creating a Perl hash initially. Just assign the new item to the hash with the correct syntax, and you're in business.
In the following sample code I show how this is done by creating a hash named prices
. The hash key is the name of a product, like pizza
, and the hash value is the price of that product. Here's my Perl hash sample code:
#!/usr/bin/perl # # add items to the "prices" hash # $prices{"pizza"} = 12.00; $prices{"coke"} = 1.25; $prices{"sandwich"} = 3.00; # # print the hash data # foreach $food_item (keys %prices) { print "$food_item costs $prices{$food_item}\n"; }
As you can see, in the first part of the code I create the prices
hash using the Perl hash syntax, like these lines of code:
$prices{"pizza"} = 12.00; $prices{"coke"} = 1.25; $prices{"sandwich"} = 3.00;
Then in the second part of my example code I print the items that are stored in the hash using the keys
and foreach
operators. As a result, the print
statement inside the foreach
loop prints the following output:
sandwich costs 3 pizza costs 12 coke costs 1.25
Related Perl hash tutorials
I hope you found this short Perl hash tutorial helpful. We have many more Perl hash tutorials on this site, including the following:
Getting started Perl hash tutorials:
- Perl hash introduction/tutorial
- Perl foreach and while: how to loop over the elements in a Perl hash
- Perl hash add - How to add an element to a Perl hash
- How to print each element in a Perl hash
More advanced Perl hash tutorials:
The hash in Perl - hash sorting tutorials: