Perl hash add element - How to add an element to a Perl hash

Perl hash "add" FAQ: How do I add a new element to a Perl hash? (Or, How do I push a new element onto a Perl hash?)

The Perl hash is a cool programming construct, and was very unique when I was learning programming languages in the late 1980s. A Perl hash is basically an array, but the keys of the array are strings instead of numbers.

Basic Perl hash "add element" syntax

To add a new element to a Perl hash, you use the following general 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.

To add more elements to the Perl hash, just use that same syntax over and over, like this:

$prices{'coke'} = 1.25;
$prices{'sandwich'} = 3.00;

(Note that there is no "Perl push" syntax for adding a new element to a Perl hash, but because people ask me that so many times, I wanted to make sure I mentioned it here.)

A complete Perl hash add element example

To help demonstrate this better, here's the source code for a complete script that shows how to add elements to a Perl hash, and then shows a simple way to traverse the hash and print each hash element (each key/value pair):

#!/usr/bin/perl

#-----------------------------------------
# perl-hash-add.pl
# created by alvin alexander, devdaily.com
#-----------------------------------------

# create a perl hash

$prices{'pizza'} = 12.00;
$prices{'coke'} = 1.25;
$prices{'sandwich'} = 3.00;

# traverse the perl hash and print
# the key/value pairs

print "\nforeach output:\n";
foreach $key (keys %prices)
{
  # do whatever you want with $key and $value here ...
  $value = $prices{$key};
  print "  $key costs $value\n";
}

I hope this Perl hash add element tutorial is a helpful reference for you.

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:

More advanced Perl hash tutorials:

The hash in Perl - hash sorting tutorials: