开发者

References in Perl: Array of Hashes

开发者 https://www.devze.com 2023-01-07 18:37 出处:网络
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 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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消