How to create and use a hash in Perl

Home > Search > How-to

A hash, or more technically an associative array, assigns a key to a value.

%food = ('fruit',banana,'vegetable',onion,'grain',bread);


The hash could also be written like this, which may be easier for some people to read.

$food(fruit)     = banana;
$food(vegetable) = onion;
$food(grain)     = bread;


You can then print the value of a hash item. For example, the following will print "banana".

print $food{fruit};


Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

Please enter in the box below so that we can be sure you are a human.