开发者

In Perl, when is it passing by value/reference? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate: Why is Perl foreach variable assignment modifying the values in the array?

It seems a sub routine parameter is passed by value, but in the following example it's passing by reference:

@a = (3,5,7);
foreach my $b (@a) {
    $b = 8;
}
print "@a"; # 888

So what's Perl's principle in designing this so开发者_运维问答 that we can know well whether we are now dealing with a copy of original data or not?


Your example isn't a subroutine, so it's not really "passing" anything.

What you have is an array (3, 5, 7), and each my $b is a reference to each element of the array. You can think of this happening because you are iterating over the elements in the array, not iterating over copies of them.

Anytime you reference elements in an array, you are referencing THE element, not a copy.


Perl treats scalars somewhat magically in that context, and sorta "pretends" that it's passing them by reference. Sometimes it's useful, other times it's a pain in the rear.

Ah-ha, found a reference and explanation in Programming Perl, chapter 4:

If LIST consists entirely of assignable values (meaning variables, generally, not enumerated constants), you can modify each of those variables by modifying VAR inside the loop. That's because the foreach loop index variable is an implicit alias for each item in the list that you're looping over.

And thanks to ysth for the following reference from the official perl documentation:

If any element of LIST is an lvalue, you can modify it by modifying VAR inside the loop. Conversely, if any element of LIST is NOT an lvalue, any attempt to modify that element will fail. In other words, the foreach loop index variable is an implicit alias for each item in the list that you're looping over.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜