In Perl, how do you access a value from a link in a hashrefs array?

I have an array of links to anonymous hashes. From the reference to this $allDirArray , I want to access the value corresponding to the 'dir' key. I am currently getting the error message:

  Can't use string ("HASH (0x100878050)") as a HASH ref while "strict refs" 
 in use at nameOfProgram.pl line 148.

My code is:

 my $tempDir = ${$allDirArray}[$i]{'dir'}; 
+4
source share
5 answers

The error message suggests that you are actually trying to use the string " HASH(0x100878050) " as hashref. Therefore, I suspect that you have managed to somehow strengthen your hashes (i.e. you used them as strings, and Perl turned them into strings for you). One way this can happen is to assign the hash hash to the hash hash (hash keys can only be strings) or by quoting the variables in the assignment, like this $array[0] = "$hashref" .

Thus, inside ${$allDirArray}[$i] there is a line containing "HASH (0x100878050)", literally this is on the line. Not a hash.

The best bet to confirm this is probably to reset the data structure. You can do this with Data :: Dumper :

 use Data::Dumper; print Dumper($allDirArray); 
+6
source
  $allDirArray->[$i]->{dir} 

See perldoc perlreftut .

Now, I think Dan has the right diagnosis for your problem. So the frequently asked questions. Is it wrong to always indicate "$ vars"? .

+3
source

I could not understand that there was a problem with the code you quoted, so I wrote a short test script and passed it through Perl.

 #! perl use warnings; use strict; my $allDirArray = [{dir => "b"},{c => "d"}]; my $i = 0; my $tempDir = ${$allDirArray}[$i]{'dir'}; print "$tempDir\n"; 

As stated above, using Perl 5.10 in Cygwin, the program ran as follows:

 $ perl allarraydir.pl b 

The error message was not printed. See http://codepad.org/pH4eyMlt

Edit

After including the telemachus offer, I added the following code at the end of the above program,

 # The following addition was included re telemachus comment my @allDirArray2 = ({dir => "b"},{c => "d"}); $tempDir = ${$allDirArray2}[$i]{'dir'}; print "$tempDir\n"; 

ran it again and received the following error message:

  $ perl allarraydir.pl
 Global symbol "$ allDirArray2" requires explicit package name at 
 allarraydir.pl line 10.
 Execution of allarraydir.pl aborted due to compilation errors.

(This should be a comment on your question, not an answer, but the code is too long.)

+2
source
 $$allDirArray[$i]->{'dir'} 
0
source

Somehow you managed to turn your anonymous hash into a string.

Here is a brief example that causes this error.

 use strict; use warnings; my $allDirArray = [ ''.{ 'dir' => 'somedir' } ]; my $tempdir = ${$allDirArray}[0]{'dir'}; # or my $tempdir = $allDirArray->[0]{'dir'}; 
  Can't use string ("HASH (0x8555168)") as a HASH ref while "strict refs" in use at nameOfProgram.pl line 8.
0
source

All Articles