Tuesday, April 7, 2009

Perl: Get only all Keys from a hash

Share at Facebook

If you want to get all the key names from your hash at Perl, you can easily use the keys function. This will return only all the keys from the Perl hash as an array. For example the below code.


%my_hash = ('key_one' => '1',
'key_two' => '2',
'key_three' => '3');

foreach my $key (keys %my_hash){
print "$key\n";

You can use sort() reverse() functions to sort or revers the array. That case the print from foreach loop will be as below.

foreach my $key (reverse keys %my_hash){
print "$key\n";

You can also use another array to copy the key names from your hash easily. For example

my @array = keys( %my_hash);
$\ = $/;
print for @array;


Anonymous said...

Hmm that last one doesn't seem to quite work. I'm getting 'Assignment to both a list and a scalar' when attempting to use @array = keys (%hash);

Jai said...

Excellent info,

My Query ? I have two Arrays want to make those two arrays to be part of one hash.

Ex: @arr1 and @arr2

want to save @arr1 all elements as keys and @arr2 all elements as values.

Is this possible ?

if so kindly help/update me.

Jai said...

Superb Information,

But i got a different requirement, i have 2 arrays want to combine these
with a single hash.

Ex: @arr1 and @arr2 and want to these to be in a single hash like
@arr1 all elements of this need be keys and @arr2 all elements of this array
need to be elements.

Is this possible, if so kindly help/update me.