From: Sal on 13 Aug 2010 20:16 #!/usr/bin/perl use strict; use warnings; my %sum = {}; for (my $i = 1; $i <= 6; $i++) { for (my $j = 1; $j <= 6; $j++) { for (my $k = 1; $k <= 6; $k++) { my $tot = $i+$j+$k; my $key = "$i " . "$j " . "$k "; $sum{$key} = $tot; print "$i " . "$j " . "$k " . " $tot\n"; } } } foreach my $key (sort keys %sum) { print "$key => $sum{$key}\n"; } When the above is executed it first prints the entire hash, then returns the error: Use of uninitialized value $sum{"HASH(0x95fe818)"} in concatenation (.) or string at ./3dice.pl line 19. HASH(0x95fe818) => Why is the last hash value blank?
From: Don Piven on 13 Aug 2010 20:37 On 08/13/2010 07:16 PM, Sal wrote: > #!/usr/bin/perl > > use strict; > use warnings; > > my %sum = {}; > [code omitted] > > foreach my $key (sort keys %sum) { > print "$key => $sum{$key}\n"; > } > > When the above is executed it first prints the entire hash, then > returns the error: > > Use of uninitialized value $sum{"HASH(0x95fe818)"} in concatenation > (.) or string at ./3dice.pl line 19. > HASH(0x95fe818) => > > Why is the last hash value blank? The line "my %sum = {};" doesn't initialize %sum to an empty hash. {} returns a reference to an empty hash, so that reference, stringified, becomes a key in %sum and, since no value is provided in %sum's initializer list, that key's value becomes undef. You could just declare %sum without an initializer, or initialize it with an empty list: "my %sum = ();". Don
From: Ben Morrow on 13 Aug 2010 20:41 Quoth Sal <here(a)softcom.net>: > #!/usr/bin/perl > > use strict; > use warnings; > > my %sum = {}; This line is wrong. {} creates a new anonymous hashref; this is then stringified and inserted into the hash as a key with no value. Effectively this line is equivalent to my %sum = ("HASH(0xDEADBEEF)" => undef); If you want an empty hash, just say my %sum; Ben
|
Pages: 1 Prev: FAQ 4.74 How do I print out or copy a recursive data structure? |