Error trying to loop through array of hashes in Perl
This has been asked before a couple of times, but none of those answers seem to work for my situation.
My code:
open(FILE, "<", $fileb) or die "File not openable: $!";
while (<FILE>) {
$filebmeta[$line] = (data => $_, match => -1);
$line++;
}
close(FILE);
$line = 0;
for my $hashref (@filebmeta) {
print "$hashref->{data}\n";
}
when I run this code it spits out: 'Can't use string ("-1") as a HASH ref while "strict refs" in use at ./partc.pl line 152.'
Any idea why this is happening? I don't seem to be able to dereference the h开发者_开发技巧ash properly in the loop.
The elements of the array need to be hashrefs, so your assigment statement needs to use curly brackets:
$filebmeta[$line] = {data => $_, match => -1};
You code is assigning a list to the array, so it just gets the last element in the list which is the -1
. Thus your error message.
Your expression (data => $_, match => -1)
does not create a hashref, it creates a list. You probably meant {data => $_, match => -1}
You mean besides all the undefined variables in your code? Read perlreftut and pay attention to the syntax.
精彩评论