views:

104

answers:

1

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;
}
+8  A: 

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.

martin clayton
This common error comes from not understanding context. Assignment to a scalar produces a scalar context, thus `@_` is evaluated as a scalar (which yields the length).
daotoad