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

后端 未结 7 1953
走了就别回头了
走了就别回头了 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:30

    Trying to create copies by saying

    my %hash = %{$ref_hash};
    

    is even more dangerous than using the hashref. This is because it only creates a shallow copy. This will lead you to thinking it is okay to modify the hash, but if it contains references they will modify the original data structure. I find it better to just pass references and be careful, but if you really want to make sure you have a copy of the reference passed in you can say:

    use Storable qw/dclone/;
    
    my %hash = %{dclone $ref_hash};
    

提交回复
热议问题