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

后端 未结 9 975
囚心锁ツ
囚心锁ツ 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 06:04

    Use the folowing sub to get hash or hashref - whatever passed :)

    sub get_args { ref( $_[0] ) ? shift() : ( @_ % 2 ) ? {} : {@_}; }
    sub PrintAA
    {
      my $test = shift;
      my $aa = get_args(@_);;
      #then
      $aa->{somearg} #do something
      $aa->{anotherearg} #do something
    
    }
    

    Call your function like this:

    printAA($firstarg,somearg=>1, anotherarg=>2)
    

    Or like this(no matter):

    printAA($firstarg,{somearg=>1, anotherarg=>2})
    

    Or even like this(no matter):

    my(%hash) = ( 'aaa' => 1, 'bbb' => 'balls', 'ccc' => \PrintAA );
    
    PrintAA("test", %hash);
    

    Cheers!

提交回复
热议问题