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

后端 未结 9 978
囚心锁ツ
囚心锁ツ 2020-12-24 05:36

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, h

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-24 05:59

    It looks like you should pass in a reference to a hash.

    sub PrintAA
    {
       my $test = shift;
       my $aa = shift;
       if (ref($aa) != "HASH") { die "bad arg!" }
       ....
    }
    
    PrintAA($foo, \%bar);
    

    The reason you can't do a

    my %aa = shift;
    

    is because Perl flattens all the arguments to a subroutine into one list, @_. Every element is copied, so passing in by reference avoids those copies as well.

提交回复
热议问题