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

后端 未结 9 948
囚心锁ツ
囚心锁ツ 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:05

    As usual there are several ways. Here is what Perl Best Practices, that most revered of style pointers, has to say about passing parameters to functions:

    Use a hash of named arguments for any subroutine that has more than three parameters

    But since you have only two, you could get away ;) with passing them directly like this:

    my $scalar = 5;
    my %hash = (a => 1, b => 2, c => 3);
    
    func($scalar, %hash)
    

    And function is defined like this:

    sub func {
        my $scalar_var = shift;
        my %hash_var = @_;
    
        ... Do something ...
    }
    

    It could be more useful if you could show some code.

提交回复
热议问题