Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl, how do you access a value from a reference in an array of hashrefs?

Tags:

reference

perl

I have an array of references to anonymous hashes. From the reference to that array, $allDirArray, I want to access the value corresponding to the key 'dir'. Currently I am getting the error:

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

My code:

my $tempDir = ${$allDirArray}[$i]{'dir'};
like image 326
mel Avatar asked Dec 23 '22 08:12

mel


1 Answers

The error message suggests you're actually trying to use the string "HASH(0x100878050)" as a hashref. So I suspect you've somehow managed to stringify your hashes (ie, you used them as strings, and Perl turned them into strings for you). One way this can happen is if you assign a hashref to a hash key (hash keys can only be strings), or by quoting variables in an assignment like this $array[0] = "$hashref".

So inside ${$allDirArray}[$i] is a string containing "HASH(0x100878050)", literally that, in a string. Not a hash.

Best bet to confirm this is probably to dump the data structure. You can do this with Data::Dumper:

use Data::Dumper;
print Dumper($allDirArray);
like image 197
Dan Avatar answered May 03 '23 01:05

Dan