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;
}
To get a hash reference, use the {key=>value} syntax instead, or prefix your variable name with a backslash like: %hash. Dereference a hash with %$hashref, with the $arrayref->{key} arrow for value references, or the %{array_ref_expression} syntax.
Creating a reference to a Perl array If we have an array called @names, we can create a reference to the array using a back-slash \ in-front of the variable: my $names_ref = \@names;. We use the _ref extension so it will stand out for us that we expect to have a reference in that scalar.
To add another hash to an array, we first initialize the array with our data. Then, we use push to push the new hash to the array. The new hash should have all of its data. As shown below, you can see the difference between the two arrays before and after pushing a new hash.
Dereference a HASH First we print it out directly so you can see it is really a reference to a HASH. Then we print out the content using the standard Data::Dumper module. Then we de-reference it by putting a % sign in-front of it %$hr and copy the content to another variable called %h.
The line
my $garage = @_;
assigns the length of @_
to garage. In the call to the testDriveCars
method you pass a single arg, hence the length is one, hence your error message about "1"
.
You could write
my ( $garage ) = @_;
or perhaps
my $garage = shift;
instead.
There's a missing semicolon in the posting too - after the assignment of @garage
.
See perldoc perlsub for the details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With