issue accessing elements of hash in perl

妖精的绣舞 提交于 2021-02-08 05:30:11

问题


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


回答1:


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:

  • perlreftut
  • perllol



回答2:


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.



来源:https://stackoverflow.com/questions/62145933/issue-accessing-elements-of-hash-in-perl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!