SPUG:object in a hash
Jeremy Kahn
kahn at cpan.org
Wed Jun 4 12:14:17 CDT 2003
Hash keys are always strings. Below I (1) gloss the code you wrote in
English, (2) provide some debugging pointers, and (3) provide a
suggestion about where to find better documentation of the issues you're
tangling with.
(1) I gloss in English:
Line 1:
get a new RecordObject (with parameters),
and store a reference to that object in $infoRecord,
AND go to the %INFOHASH and increment the value associated with the
stringified version of that reference ("RecordObject=Hash0x43debc3" or
something similar).
Note that INFOHASH now stores ( "RecordObject=Hash0x43debc3" => 1);
There's nothing fancy about that value in %INFOHASH -- and it's JUST A
STRING now. Note the real reference (in $infoRecord) is still the real
reference.
Line 2: print the stringified version of that reference
Line 3: print the value associated with the key "comName1" within the
hash that $infoRecord points to. This is sometimes called "dereferencing
$infoRecord"
line 8: prints the key (which, per line 1, is a stringified reference).
line 9: prints the value (probably 1)
line 10: tries to dereference "RecordObject=Hash0x43debc3" -- which
ISN'T a reference, only a string.
(2) Debugging pointers:
You'll see the difference if (instead of print()) you try
line 2.5: print ref($infoRecord), "\n"
line 9.5: print ref($key), "\n";
My suggestion is that you not use print() as your debugging tool, but
Data::Dumper. Data::Dumper does very different things with lines 3 and
10, I'll bet. If you learn the debugger (perldoc perldebug), you could
use the 'x' command to dump out the contents of a scalar as well or
instead of Data::Dumper.
(3): Addressing the problem you're trying to solve, and provide doc
pointers:
As far as what you're *trying* to do here, I'm not sure, but I would
suggest using the object as the *value* of the hash, not the key.
It's also worth following up on perldoc perldsc. What I think you're
aiming for is a "hash of complex records" (there's a section by that name).
Hope that helps.
--Jeremy
mkorb wrote:
> Here is a script slice
>
> 1 $INFOHASH{$infoRecord = new RecordObject(\@columnArray,\@infoArray)}++;;
>
> 2 print "$infoRecord\n";
>
> 3 print "$infoRecord->{comName1}\n";
>
> 4
>
> 5
>
> 6 foreach my $key (keys %INFOHASH)
>
> 7 {
>
> 8 print "$key\n";
>
> 9 print "$INFOHASH{$key}\n";
>
> 10 print "$key->{comName1}\n";
>
> 11 }
>
> Line 2 prints the same as line 8
>
> Line 3 prints the correct value, so does line 9
>
> Line 10 gives me the following error “can not use String RecordObject=
> Hash….. as Hashref while strict refs in use.
>
> Isn’t line 10 the same as Line 3, see Line 2 and 8
>
> What am I overlooking?
>
> Thanks
>
More information about the spug-list
mailing list