Reputation: 169
I have array of hash code where I am trying to print the key from array of hash in PERL. Following is the code
my $list = [];
$list = [
{
Test => “Value”
}
];
my ($get_list_key) = map { $_ } @$list;
print $get_list_key;
I get the output as:
HASH(0x10bdfd0)
I want the output as:
$list = [
"Test"
];
Can anyone please help.
Thanks in advance
Upvotes: 0
Views: 1907
Reputation: 69224
$list = [ { Test => “Value” } ];
Here, you are setting $list
to an array reference. The referenced array has only one element, which is an reference to a hash. As an aside, you're using the wrong quote characters to define "Value"
- you need to use straight quote marks.
my ($get_list_key) = map { $_ } @$list;
You dereference the array reference, to get an array that you can use with map
. But, as we said above, the single element in the array is a hash reference. In the map
block you just return $_
, which will be that hash reference - so you get a single hash reference back in your $get_list_key
variable.
You need to do something cleverer in the map
block. You want to get the keys of the referenced hash. To do that, you need to do two things: 1/ dereference the hash reference and 2/ use the keys
functions.
my ($get_list_key) = map { keys %$_ } @$list;
That will get you the single key ("Test") in your $get_key_list
variable. But that's not what you want. You want a reference to an array which contains all of the keys. To do that, you need to surround the whole expression on the right hand side of the assignment operator with an anonymous array constructor ([ ... ]
). So, eventually, you end up with the code in Håkon's answer.
my ($get_list_key) = [ map { keys %$_ } @$list ];
Upvotes: 4
Reputation: 40718
Try this:
use strict;
use warnings;
use Data::Dumper;
my $list = [
{
Test => "Value"
}
];
my $get_list_key = [ map { keys %$_ } @$list] ;
print Dumper( $get_list_key );
Output:
$VAR1 = [
'Test'
];
Upvotes: 3