Perl:Access values of hash inside a hash

試著忘記壹切 提交于 2020-01-02 09:59:31

问题


I have just picked up Perl. I have a little confusion with accessing hash values. Below is the code where I am trying to access the values of a hash inside a hash. Since am using a simple text editor to code, I am not able to figure out what can be the problem. Please help

my %box = (
    Milk => {
        A => 5,
        B => 10,
        C => 20,
    },
    Chocolate => {
        AB => 10,
        BC => 25,
        CD => 40,
    },
);

foreach my $box_key(keys %box) {
    foreach my $inside_key (keys %box{box_key})
    print "$box_key"."_$inside_key""is for rupees $box{box_key}{inside_key}";
}

回答1:


ikegami has explained it very well and I feel that you are still missing something in your code that's why you are having a problem, try the below code, hope it helps you.

my %box = (
    Milk => {
        A => 5,
        B => 10,
        C => 20,
    },
    Chocolate => {
        AB => 10,
        BC => 25,
        CD => 40,
    },
);

foreach my $box_key(keys %box) {
    foreach my $inside_key (keys $box{$box_key}) {
      print "${box_key}_$inside_key is for rupees $box{$box_key}{$inside_key}\n";

    }
}

Output:

Chocolate_CD is for rupees 40
Chocolate_BC is for rupees 25
Chocolate_AB is for rupees 10
Milk_A is for rupees 5
Milk_C is for rupees 20
Milk_B is for rupees 10



回答2:


If the syntax is

keys %hash

for a hash, it's

keys %{ ... }

for a hash reference. In this case, the reference is stored in $box{$box_key}, so you'd use

keys %{ $box{$box_key} }

Also, you're accessing elements named box_key and inside_key in a couple of places where you actually want the elements named by $box_key and $inside_key.


Finally, you can use curlies around variable names to instruct Perl where the variable name ends.


for my $box_key (keys %box) {
   for my $inside_key (keys %{ $box{$box_key} }) {
      print "${box_key}_$inside_key is for rupees $box{$box_key}{$inside_key}\n";
   }
}


来源:https://stackoverflow.com/questions/17036955/perlaccess-values-of-hash-inside-a-hash

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