Perl - Why does looping over a hash with its keys and then printing each value lead to an uninitialized warning?

Whenever I iterate over a hash with my keys and then print each value, I get "using an uninitialized value in a concatenation (.) Or string ...". Although the hash is clearly initialized in front. The conclusion I need is printed, but I still would like to know why this leads to a warning, especially since accessing the value directly (outside the loop) works without warning.

#!/usr/bin/perl use warnings; use strict; my %fruit = (); %fruit = ('Apple' => 'Green', 'Strawberry' => 'Red', 'Mango' => 'Yellow'); #works print "An apple is $fruit{Apple} \n"; #gives warnings foreach my $key (%fruit) { print "The color of $key is $fruit{$key} \n"; } #also gives warnings foreach my $key (%fruit) { my $value = $fruit{$key}; print "$value \n"; } 

Consider the code above. I think perl sees the difference between the first print and the second print. But why? Why is there a difference between retrieving the hash value outside the loop and retrieving the value of a inside the loop?

Thanks!

+7
source share
3 answers

Using a hash in a list context gives both keys and values. Therefore, the string foreach my $key (%fruit) iterates over the key, value, value, value ...

You need foreach my $key (keys %fruit) .

+17
source

Use keys inside a for loop. e.g. foreach my $key (keys %fruit) ...

+2
source

This should be foreach my $key ( keys %fruits ) . I think this is what you really want to do.

+2
source

All Articles