I want to iterate through a reference to an array of hashes without having to make local copies, but I keep getting Can’t use string (“1”) as an ARRAY ref while “strict refs” errors. Why? How do I fix it?
sub hasGoodCar {
my @garage = (
{
model => "BMW",
year => 1999
},
{
model => "Mercedes",
year => 2000
},
);
run testDriveCars( \@garage );
}
sub testDriveCars {
my $garage = @_;
foreach my $car ( @{$garage} ) { # <=========== Can't use string ("1") as an ARRAY ref while "strict refs" error
return 1 if $car->{model} eq "BMW";
}
return 0;
}
The line
assigns the length of
@_to garage. In the call to thetestDriveCarsmethod you pass a single arg, hence the length is one, hence your error message about"1".You could write
or perhaps
instead.
There’s a missing semicolon in the posting too – after the assignment of
@garage.See perldoc perlsub for the details.