Are Perl subroutines call-by-reference or call-by-value?

后端 未结 5 1925
太阳男子
太阳男子 2020-12-08 00:59

I\'m trying to figure out Perl subroutines and how they work. From perlsub I understand that subroutines are call-by-reference and that an assignment (like my(@copy) =

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 01:21

    Perl does not pass the array or hash itself by reference, it unfurls the entries (the array elements, or the hash keys and values) into a list and passes this list to the function. @_ then allows you to access the scalars as references.

    This is roughly the same as writing:

    @a = (1, 2, 3);
    
    $b = \$a[2];
    
    ${$b} = 4;
    
    @a now [1, 2, 4];
    

    You'll note that in the first case you were not able to add an extra item to @a, all that happened was that you modified the members of @a that already existed. In the second case, the hash keys don't really exist in the hash as scalars, so these need to be created as copies in temporary scalars when the expanded list of the hash is created to be passed into the function. Modifying this temporary scalar will not modify the hash key, as it is not the hash key.

    If you want to modify an array or hash in a function, you will need to pass a reference to the container:

    change(\%foo);
    
    sub change {
       $_[0]->{a} = 1;
    }
    

提交回复
热议问题