Perl:访问散列内的散列值

问题描述:

我刚刚拿起Perl。
我对访问哈希值有点困惑。下面是我尝试访问散列内散列值的代码。
由于我正在使用一个简单的文本编辑器进行编码,所以我无法弄清楚可能是什么问题。请帮助

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}";
}


ikegami解释得非常好我觉得你仍然在代码中遗漏了一些东西,这就是为什么你有问题,请尝试下面的代码,希望它能帮助你。

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";

    }
}

输出:

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