in reply to Re: can't use string as hash ref
in thread can't use string as hash ref

I think your explanations are very misleading ...

my %hash; my @array = (1..100); # this will be ok $hash{\@array} = 42;
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)".

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.

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;
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.

Witness:

use strict; my %hash; my @array = (1..100); $hash{\@array} = {}; $hash{\@array}{1} = 42;
This does not produce an error (but I would not say it is ok just because of that).

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

    Good point is made. Just wanted to summarize it. Every time when you see "Can't use something as reference to something" error, search for the existing element of the hash or array which is not reference as you expect it to be.

    Non-existing elements are automatically created by perl for you, and probably this is what is confusing you.