Tony Xu
Tony Xu

Reputation: 3081

Why perl hash does not take certain string variables as its key?

When I try to assign a value to multiple level hash

        use strict;
        # multi step before following code

        $res{cccc}{1}{sense} = '+'; # no problem
        my $ttsid = 'NZAEMG01000001';
        $res{$ttsid}{1}{sense} = '+'; # no problem
        $ttsid = 'NZAEMG01000001.1';
        $res{$ttsid}{1}{sense} = '+'; # no problem
        print "before sid is $sid\n"; # print out NZ_AEMG01000001t1

At this step, program runs well

        $res{$sid}{1}{sense} = '+'; # even this gets problem too

However, when I add this line into program, I got error

 Can't use string ("57/128") as a HASH ref while "strict refs" in use

Test a bit more with following

        $sid = 'placement'; # result
        $res{$sid}{1}{sense} = '+';

This has no problem. So it looks to me, the line

        $sid = 'placement'; # result

changed $sid value from NZ_AEMG01000001t1 to placement, and this makes the line

        $res{$sid}{1}{sense} = '+';

works. This kind of translates into

        $res{'NZ_AEMG01000001t1'}{1}{sense} = '+'; # Not working
        $res{'placement'}{1}{sense} = '+'; # working

Indeed, when I change $ttsid to $sid value like this

        $ttsid = 'NZ_AEMG01000001t1'; # which is $sid value
        $res{$ttsid}{1}{sense} = '+'; # has problem

This gets problem too.

Why?

Upvotes: 0

Views: 121

Answers (1)

melpomene
melpomene

Reputation: 85767

Because at some point you did the equivalent of

$res{'NZ_AEMG01000001t1'} = %some_other_hash;

which sets $res{'NZ_AEMG01000001t1'} to a string, not a reference to a (nested) hash.

The error indicates you're trying to use a string as if it were a hashref. Your data structure doesn't contain what you think it does.

Upvotes: 7

Related Questions