How do I pass a hash to a function in Perl?

rlbond picture rlbond · Apr 29, 2009 · Viewed 65.7k times · Source

I have a function that takes a variable and an associative array, but I can't seem to get them to pass right. I think this has something to do with function declarations, however I can't figure out how they work in Perl. Is there a good reference for this and how do I accomplish what I need?

I should add that it needs to be passed by reference.

sub PrintAA
{
    my $test = shift;
    my %aa   = shift;
    print $test . "\n";
    foreach (keys %aa)
    {
        print $_ . " : " . $aa{$_} . "\n";
        $aa{$_} = $aa{$_} . "+";
    }
}

Answer

Paul Tomblin picture Paul Tomblin · Apr 29, 2009

Pass the reference instead of the hash itself. As in

PrintAA("abc", \%fooHash);

sub PrintAA
{
  my $test = shift;
  my $aaRef = shift;

  print $test, "\n";
  foreach (keys %{$aaRef})
  {
    print $_, " : ", $aaRef->{$_}, "\n";
  }
}

See also perlfaq7: How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?