Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

References in Perl: Array of Hashes

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;
}
like image 652
syker Avatar asked Jul 15 '10 22:07

syker


People also ask

How do I reference a hash in Perl?

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.

How do I reference an array in Perl?

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.

How do I create an array of hashes in Perl?

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.

How do I dereference an array of hash in Perl?

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.


1 Answers

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.

like image 52
martin clayton Avatar answered Oct 23 '22 17:10

martin clayton