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,[email protected]
smt,Smith,[email protected]
Here is my script:
my @data = (
{
'mail' => '[email protected]',
'name' => 'Victor',
'id' => 'vkk'
},
{
'name' => 'Smith',
'mail' => '[email protected]',
'id' => 'smt'
}
);
print "ID,NAME,EMAIL\n"; #header
for $content (@data){
for $fields (keys %$content){
print $content->{$fields}.",";
}
print "\n";
}
CodePudding user response:
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";
}