Dr. Mu has asked for the wisdom of the Perl Monks concerning the following question:
I thought I understood hash arrays until I encountered this:
which prints:use strict; my @hashes = ({}) x 10; $hashes[$_]{$_} = 1 foreach (0 .. 9); foreach (0 .. 9) { print join(':', keys %{$hashes[$_]}), "\n" }
What gives? I was expecting it to output:6:3:7:9:2:8:1:4:0:5 6:3:7:9:2:8:1:4:0:5 6:3:7:9:2:8:1:4:0:5 6:3:7:9:2:8:1:4:0:5 6:3:7:9:2:8:1:4:0:5 6:3:7:9:2:8:1:4:0:5 6:3:7:9:2:8:1:4:0:5 6:3:7:9:2:8:1:4:0:5 6:3:7:9:2:8:1:4:0:5 6:3:7:9:2:8:1:4:0:5
('Using ActivePerl 5.8.4 on Win XP.)0 1 2 3 4 5 6 7 8 9
Thanks,
-Phil
Edit: Oh nevermind. I know what the problem is: every element of the array contains a reference to the same hash. D'oh!
This fixes the problem:
my @hashes = map{{}} (0 .. 9);
-Phil
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Array of hashes misbehaving?
by Eliya (Vicar) on May 23, 2012 at 22:22 UTC | |
by Dr. Mu (Hermit) on May 23, 2012 at 22:58 UTC | |
Re: Array of hashes misbehaving?
by ikegami (Patriarch) on May 23, 2012 at 22:33 UTC | |
by Dr. Mu (Hermit) on May 23, 2012 at 22:57 UTC |
Back to
Seekers of Perl Wisdom