Paul IT
Paul IT

Reputation: 85

issue accessing elements of hash in perl

I have the below hash:

my %releaseMap = {"rel1.2.3" => {
                                    "supporedPorts" => ["lnx86", "lnppc"],
                                    "branch"        => ["DEV"],
                                },

                  "rel2.4" =>   {
                                    "supporedPorts" => ["lnx86", "lnppc"],
                                    "branch"        => ["DEV"],
                                }
                 };

I want to get the values rel1.2.3 and rel2.4 in the variable $rel, I want to get the values lnx86 and lnppc in $port and I want to get the value DEV in $branch.

I am new to the Hash concept in perl, I am not able to figure out how this can be done.

Can someone please help. Thanks

Upvotes: 2

Views: 106

Answers (2)

Dave Cross
Dave Cross

Reputation: 69224

A hash is initialised from a list:

my %hash = ( key => value, ... );

A hash reference is initialised using the anonymous hash constructor:

my $hash_ref = { key => value, ... };

You are initialising your hash with an anonymous hash constructor. This does not work as you expect it. You end up with a hash containing a single key (which is the stringification of the anonymous hash reference:

my %hash = { key => value, ... };

If you change your code to this:

my %releaseMap = ("rel1.2.3" => {
                                    "supporedPorts" => ["lnx86", "lnppc"],
                                    "branch"        => ["DEV"],
                                },

                  "rel2.4" =>   {
                                    "supporedPorts" => ["lnx86", "lnppc"],
                                    "branch"        => ["DEV"],
                                }
                 );

Then things get easier. You can start with:

foreach my $key (keys %releaseMap) {
  say $key;
}

Also, add use strict and use warnings to your code. They will catch a lot of problems for you.

Upvotes: 2

ikegami
ikegami

Reputation: 385556

Assuming you really have

my %releaseMap = ("rel1.2.3" => {
                                    "supporedPorts" => ["lnx86", "lnppc"],
                                    "branch"        => ["DEV"],
                                },

                  "rel2.4" =>   {
                                    "supporedPorts" => ["lnx86", "lnppc"],
                                    "branch"        => ["DEV"],
                                }
                 );

You can use

for my $rel_id (keys(%releaseMap)) {
   my $rel = $releaseMap{$rel_id};

   my $ports    = $rel->{supporedPorts};
   my $branches = $rel->{branch};

   say "[$rel_id] ports = @$ports; branches = @$branches";
}

Docs:

Upvotes: 5

Related Questions