Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Recently one of my code gave the err message
Can't use string ("query") as an ARRAY ref while "strict refs" in use at ...
I have checked the file and the point where it was failing was when the file had the query as "query" The file has multiple number of fields seperated by a fixed delimiter so the point where it failed was in the line
query us 123 --> this line it failed queue ca 456
A snippet of the code which i used is as follows
if ($query eq $hash{'query'}){ push @{$hash{$query}},{'domain' => $domain ,'count' => $count} +; $tot_count += $count; } else{ my $qid = $hash{'query'}; .... some operations %hash=(); $hash{'query'}= $query; push @{$hash{$query}},{'domain' => $domain ,'count' => $count} +; $tot_count = $count; }
I have fixed the code and changed the hash structure and it works fine now.
But i do not under stand why the error would be thrown if we have to assign $hash{'query'} = "query";
Can the knowledgable monks explain me what does the error mean and why it failed.

Edit by GrandFather - replaced pre tags with code tags, to prevent distortion of site layout and allow code extraction.

Replies are listed 'Best First'.
Re: Can't use string ("query") as an ARRAY ref error
by ikegami (Patriarch) on Aug 28, 2009 at 00:46 UTC

    "@{ $hash{$query} }" means "the array referenced by the reference stored in $hash{$query}". However, $hash{$query} does not contain a reference to an array. It contains the string "query".

    If $hash{$query} is undefined and @{ $hash{$query} } is used as an lvalue (like when it's an argument to push), an array will automatically be created and a reference to that array will be stored in $hash{$query}. This is called autovivification.

    Get rid of the line $hash{'query'}= $query; (to allow autovivification).

      Yeah , I have modified the code but my doubt is why it doesnot work when the query itself is "query".
      it worked fine till the point where the query was like "abc" "perl" etc.

        What you've showed us can't work if $query contains the string "query".

        To get into the "then" part, $hash{query} must contain the string "query", which will cause the following @{$hash{$query}} to fail.

        If you get into the "else" part, $hash{query} is set to the string "query", which will cause the following @{$hash{$query}} to fail.