Extracting Keys and Values from Hash in Perl

PERLServer Side ProgrammingProgramming Scripts

You can get a list of all of the keys from a hash in Perl by using keys function, which has the following syntax −

keys %HASH

This function returns an array of all the keys of the named hash. Following is the example −

Example

 Live Demo

#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
@names = keys %data;
print "$names[0]\n";
print "$names[1]\n";
print "$names[2]\n";

Output

This will produce the following result −

Lisa
John Paul
Kumar

Similarly, you can use values function to get a list of all the values. This function has the following syntax −

Syntax

values %HASH

This function returns a normal array consisting of all the values of the named hash. Following is the example −

Example

 Live Demo

#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
@ages = values %data;
print "$ages[0]\n";
print "$ages[1]\n";
print "$ages[2]\n";

Output

This will produce the following result −

30
45
40
raja
Published on 29-Nov-2019 05:45:18
Advertisements