What's the best Perl practice for returning hashes from functions?

后端 未结 7 1958
走了就别回头了
走了就别回头了 2021-02-04 07:31

I am mulling over a best practice for passing hash references for return data to/from functions.

On the one hand, it seems intuitive to pass only input values to a fun

7条回答
  •  名媛妹妹
    2021-02-04 08:21

    The first one is better:

    my ($ref_array,$ref_hash) = $this->getData('input');
    

    The reasons are:

    • in the second case, getData() needs to check the data structures to make sure they are empty
    • you have freedom to return undef as a special value
    • it looks more Perl-idiomatic.

    Note: the lines

    @array = @{$ref_array};
    %hash = %{$ref_hash};
    

    are questionable, since you shallow-copy the whole data structures here. You can use references everywhere where you need array/hash, using -> operator for convenience.

提交回复
热议问题