I have array of hashes and need to iterate and print the values in the sequence – id,name,mailid.
But when I print the content of keys, its keep shuffling. How do I print the conetent like below:
ID,NAME,EMAIL
vkk,Victor,vkk@test.com
smt,Smith,smt@test.com
Here is my script:
my @data = (
{
'mail' => 'vkk@test.com',
'name' => 'Victor',
'id' => 'vkk'
},
{
'name' => 'Smith',
'mail' => 'smt@test.com',
'id' => 'smt'
}
);
print "ID,NAME,EMAIL\n"; #header
for $content (@data){
for $fields (keys %$content){
print $content->{$fields}.",";
}
print "\n";
}
>Solution :
The documentation for keys() says this:
Hash entries are returned in an apparently random order.
So if you want to extract the data in a specific order, then you should specify that order.
for $content (@data){
for $fields (qw(id name mail)) {
print $content->{$fields}.",";
}
print "\n";
}
Or use a hash slice to simplify the code:
for $content (@data) {
print join(',', @{$content}{qw(id name mail)}), "\n";
}