zentara has asked for the wisdom of the Perl Monks concerning the following question:
So I've read all the stuff on auto-vivication, and similar posts. What I end up doing is falling back on a little trick I've stumbled upon, and just resort to using it to get around the error. My question is:
Is it correct to think about it this way, or am I just lucky? :-)
My idea is you can't create "depth" in a hash, by assigning a value to it. The code below shows the basic idea.
Usually I have a base item as a hash, like $box{$X}{$Y}{$z}. Now the problem comes when you want to attach data to it, if the "depth" for what you want to assign a value to dosn't exist yet, it gives an error; but if you "artificially" create the depth, even if it's undef, it all works well.
So in the code, I want to add a {'text'} key to the hash, but it won't let me, until I create a fake key {'rect'} at that level, then all goes well. But then my "base" turns from $box{$X}{$Y}{$z} to $box{$X}{$Y}{$z}{'rect'}. This is just an annoyance, but it always seems to work. Does anyone see pitfalls in this approach.?
#!/usr/bin/perl use warnings; use strict; # demonstrates strict hash refs # Commonly seen error # Can't use string ("1") as a HASH ref while "strict refs" in use at . +/z line my %box; my $x = 10; my $y = 10; my $z = 1; foreach my $X ( 0 .. $x ) { foreach my $Y ( 0 .. $y ) { # you cannot create a new hash depth by assigning # a value to it $box{$X}{$Y}{$z} = 1; #dosn't work and causes err +or below # $box{$X}{$Y}{$z}{'rect'} = 1 ; #works # $box{$X}{$Y}{$z}{'rect'} = undef ; #works $box{$X}{$Y}{$z}{'text'} = 2; #this gives strict refs error + } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: The "no strict refs" problem revisited.
by Joost (Canon) on May 21, 2004 at 22:21 UTC | |
|
Re: The "no strict refs" problem revisited.
by jonadab (Parson) on May 22, 2004 at 01:31 UTC | |
|
Re: The "no strict refs" problem revisited.
by zentara (Cardinal) on May 22, 2004 at 13:02 UTC |