arraysperldictionaryhashrefarrayref

How do I convert an array or a list into a hashref?


I have a list like this:

my $myV3VersionOfData = ["ZG","ZB","CXLDN",...];

and I want to convert it into a dictionary like this:

my $entries = {
'ZG' => {
'value' => 'ZG'
},
'ZB' => {
'value' => 'ZB'
},
'CXLDN' => {
'value' => 'CXLDN'
},
...
};

I tried this so far, but it doesn't work and gives me an error:

Can't use string ("ZG") as a HASH ref while "strict refs" in use at..

I understand this is occurring since I'm trying to assign the key value from the list, but how do I convert this list into a dictionary shown above?

my %genericHash;
for my $entry (@$myV3VersionOfData) {
  $genericHash{ $entry->{key} } = $entry->{value};
}

How can I achieve this? I am new to Perl, and I have tried a bunch of things but it doesn't seem to work. Can anyone please help with this?


Solution

  • Here's how I've done it for over 10 years.

    #! /usr/bin/perl
    use warnings;
    use strict;
    use Data::Dumper qw(Dumper);
    
    my %entries;
    my @myV3VersionOfData = ("ZG","ZB","CXLDN");
    foreach (@myV3VersionOfData) {
        $entries{$_}{'value'} = $_;
    }
    
    print Dumper \%entries;