in reply to Re: can't use string as hash ref
in thread can't use string as hash ref
What happens here is that \@array gets stringified, so the key in the hash is a string (not a reference!) that looks something like "ARRAY(0x987f468)".my %hash; my @array = (1..100); # this will be ok $hash{\@array} = 42;
Such a construction is (unfortunately) not causing an error, but it almost never is what you want, so it is not ok. It usually is a programming error.
What happens here is that you stringify \@array twice (resulting in the same string each time), so in $hash{\@array}{1} you try to use $hash{\@array} as a hash, but you have assigned 42 (which is not a hash) to that before. The error has nothing to do at all with \@array being used as a hash-key.my %hash; my @array = (1..100); # this will be ok $hash{\@array} = 42; # but this will issue an error, because \@array # cannot be used as a key which varies $hash{\@array}{1} = 42;
Witness:
This does not produce an error (but I would not say it is ok just because of that).use strict; my %hash; my @array = (1..100); $hash{\@array} = {}; $hash{\@array}{1} = 42;
If you want to use references as hash-keys you have to use Tie::RefHash.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: can't use string as hash ref
by andal (Hermit) on Oct 26, 2010 at 09:54 UTC |