Whenever I loop over a hash by its keys, and then printing each value, I get an "use of of uninitialized value in concatenation (.) or string..." warning. Even though the hash is clearly initialized up front. The output I want is printed, but I'd still like to know why this results in a warning, especially as accessing a value directly (outside of a loop) works without warnings.
#!/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 above code. I guess perl sees a difference between the first print and the second print. But why? Why is there a difference between retrieving the value of a hash outside of loop and retrieving the value of a has inside of a loop?
Thanks!
Instead of just having the "seen" type of hash, it can store both the count and order noticed. Basically, instead of $count{$line} having the number of times seen, $count{$line}{count} is the times seen and $count{$line}{order} is the order in which it was seen.
Extracting Keys and Values from a Hash variable The list of all the keys from a hash is provided by the keys function, in the syntax: keys %hashname . The list of all the values from a hash is provided by the values function, in the syntax: values %hashname . Both the keys and values function return an array.
keys() function in Perl returns all the keys of the HASH as a list. Order of elements in the List need not to be same always, but, it matches to the order returned by values and each function. Return: For scalar context, it returns the number of keys in the hash whereas for List context it returns a list of keys.
A hash is a set of key/value pairs. Hash variables are preceded by a percent (%) sign. To refer to a single element of a hash, you will use the hash variable name preceded by a "$" sign and followed by the "key" associated with the value in curly brackets..
Using a hash in list context yields both keys and values. Therefore the line foreach my $key (%fruit)
iterates over key, value, key, value...
What you need is foreach my $key (keys %fruit)
.
It should be foreach my $key ( keys %fruits )
. I think this is what you actually want to do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With