Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Print hash keys sequentially in Perl

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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";
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading