Creating Hashes in Perl

PERLServer Side ProgrammingProgramming Scripts

Perl Hashes are created in one of the two following ways. In the first method, you assign a value to a named key on a one-by-one basis −

$data{'John Paul'} = 45;
$data{'Lisa'} = 30;
$data{'Kumar'} = 40;

In the second case, you use a list, which is converted by taking individual pairs from the list: the first element of the pair is used as the key, and the second, as the value. For example −

%data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40);

For clarity, you can use => as an alias for, to indicate the key/value pairs as follows −

%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);

Here is one more variant of the above form, have a look at it, here all the keys have been preceded by a hyphen (-) and no quotation is required around them −

%data = (-JohnPaul => 45, -Lisa => 30, -Kumar => 40);

But it is important to note that there is a single word, i.e., without spaces keys have been used in this form of hash formation and if you build-up your hash this way then keys will be accessed using hyphen only as shown below.

$val = %data{-JohnPaul}
$val = %data{-Lisa}
raja
Published on 29-Nov-2019 05:40:16
Advertisements