Ratstail91
Ratstail91

Reputation: 29

Storing an array in a hash

So, this doesn't work, and I have no idea why. I've tried every possible variation. But nothing works. I'm ready to take a chainsaw to my server, but hopefully you can prevent that:

sub getQuestMarkers {
  #database stuff
  ...
  my %package;
  while(my ($key, $lat, $lng) = $sth->fetchrow_array()) {
    $package{$key} = ($lat,$lng);
  }

  ...
  return %package;
}

my %markers = getQuestMarkers();
while(my( $key, $value) = each %markers) {
  print "$key: @value - $value[0] $value[1]\n";
}

Upvotes: 2

Views: 58

Answers (1)

xxfelixxx
xxfelixxx

Reputation: 6592

Use brackets [ ] to create an array reference, not parens ( );

As written, your code throws away the first value $lat. Write it like this instead:

$package{$key} = [$lat,$lng];

You can pull out the values like this:

my ($lat,$lng) = @{ $package{$key} };

In your code, you could print out the values by dereferencing them:

print "$key: " . $value->[0] . " " . $value->[1] . "\n";

Have a look at perldoc perlreftut.

Upvotes: 3

Related Questions