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

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

    Arguments to functions get flattened into a single array (@_). So it's usually easiest to pass hashes to function by reference.

    To create a HASH:

    my %myhash = ( key1 => "val1", key2 => "val2" );
    

    To create a reference to that HASH:

    my $href = \%myhash
    

    To access that hash by reference;

    %$href
    

    So in your sub:

    my $myhref = shift;
    
    keys %$myhref;
    

提交回复
热议问题