Perl Hash

« Previous Tutorial Next Tutorial »

A hash in perl, is simply a set of key/value pairs. All the hash variables in perl, are preceded by percent (%) sign. You have to use hash variable name preceded by a dollar ($) sign to refer to a single element of a hash in perl, by the "key" associated with the value in the curly bracket.

Create Hash in Perl

You can create hash in two ways. In first way, you assign a value to a named key on one-by-one manner. Here is an example:

$names{'Deepak'} = 18;
$names{'Rajat'} = 16;
$names{'Ravi'} = 18;

Now, in second way, you use a list, converted by taking individual pairs from the list. The first element of the pair is used as key, and the second, is used as value. Here is an example:

%names = ('Deepak', 18, 'Rajat', 16, 'Ravi', 18);

For clarity and simplicity, you can use => as an alias for, to indicate the key/value pairs. Here is an example:

%names = ('Deepak' => 18, 'Rajat' => 16, 'Ravi' => 18);

Access Hash Elements in Perl

To access individual elements from a hash in perl, then you have to prefix the hash variable with a dollar ($) sign and then append the element key within a curly bracket after the variable's name. Here is an example:


%names = ('Deepak' => 18, 'Rajat' => 16, 'Ravi' => 18);


Here is the sample output of the above perl program:


Perl Hash Example

Here is an example program, illustrates hash in perl:


%names = ('Deepak' => 18, 'Rajat' => 16, 'Ravi' => 18);

print("\$names{'Deepak'} = $names{'Deepak'}\n");
print("\$names{'Rajat'} = $names{'Rajat'}\n");
print("\$names{'Ravi'} = $names{'Ravi'}\n");

Here is the sample output produced by the above perl program:

$names{'Deepak'} = 18
$names{'Rajat'} = 16
$names{'Ravi'} = 18

« Previous Tutorial Next Tutorial »


Quick Links
Signup - Login - Give Online Test