为什么 Perl 允许通过引用传递参数?
我想知道为什么 Perl 能够通过引用函数来传递参数? 我知道Python和Ruby都没有这样的功能。
I'm wondering why Perl has ability to pass argument by reference to function?
I know that neither Python, nor Ruby doesn't have such feature.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将一件事与另一件事区分开来是很有用的。
(1) 通过引用将参数传递给子例程。这在 Perl 中很有用,因为该语言将所有参数作为无差别的值列表传递给子例程。如果没有通过引用传递数据结构的能力,例如,采用两个列表的函数的设计者将无法将列表分开。此外,如果数据结构很大,通过引用传递它们可以提高性能。
由于 Python 和 Ruby 的设计不同,因此它们在参数传递方式上不需要这种区别。 Python 或 Ruby 中的类似方法将接收两个不同的参数(表示列表 x 和 y 的两个对象)。
(2) Perl 的行为,其中
@_
充当所传递参数的别名,允许子例程修改调用者感知的数据。Python 和 Ruby 也可以做这类事情;然而,有一些资格。 Python 区分可变和不可变对象。如果将可变的内容传递给 Python 方法(例如列表),该方法就能够修改数据结构。因此,
process_two_lists
的 Python 版本将能够同时修改x
和y
。但是,接收不可变对象(例如整数)的函数则不会。因此,直接用 Python 模拟add_ten_to_me
是行不通的。 [我相信关于 Ruby 也可以提出类似的观点,但目前我不太熟悉细节。]It's useful to distinguish one thing from another.
(1) Passing arguments to a subroutine by reference. This is useful in Perl because the language passes all arguments to a subroutine as an undifferentiated list of values. Without the ability to passed data structures by reference, the designer of a function taking two lists, for example, would not be able to keep the lists separate. In addition, if the data structures are large, passing them by reference can provide a performance gain.
Because Python and Ruby are designed differently, they don't require this distinction in how arguments are passed. A similar method in Python or Ruby would receive two distinct arguments (two objects representing lists
x
andy
).(2) Perl's behavior whereby
@_
serves as an alias to the passed arguments, allowing the subroutine to modify data as perceived by the caller.Python and Ruby can do this type of thing as well; however, there are some qualifications. Python distinguishes between mutable and immutable objects. If you pass something mutable to a Python method (a list, for example), the method is able to modify the data structure. So a Python version of
process_two_lists
would be able to modify bothx
andy
. However, a function receiving immutable objects (an integer, for example) would not. Thus, a direct Python analog ofadd_ten_to_me
would not work. [I believe that similar points could be made about Ruby, but I'm less familiar with the details at this point.]通过引用传递参数可以显着提高性能。
Passing arguments by reference can give significant performance improvements.
Perl 为您提供了选择。我认为这是 TIMTOWTDI 想法的一部分。这是一种灵活的方法,因此您可以做您需要的事情。如果您以
$_[0]
的形式访问参数,那么它是同一个对象。如果你将它移动或复制到词法中,它就是按值。所以这样想吧。大多数代码都是按值编写的,但当您需要时,可以按引用编写。
Perl gives you the choice. I think it's part of that TIMTOWTDI idea. It's a flexible method, so you can do what you need. If you access the argument as
$_[0]
then it's the same object. If you shift it or copy it to a lexical, it's by value.So think of it this way. Most code is by value, but by reference is there when you need it.