将数组传递给Perl中的函数 [英] Passing arrays to functions in Perl
问题描述
我想我误解了在Perl中传递函数的某些方面。 func(\ @ array)
和 func(@array)
?
$ b
AFAIK,在这两个函数中,参数都是通过引用传递的,在这两个函数中,我们可以在主程序中更改 @array
的元素。那有什么区别?什么时候应该使用哪个?
@array =(1,2,3);
func(@array);
func(\ @ array);
func {
...
}
<另外,我如何模仿Perl中的传值?
是使用 @_
唯一的方法吗? AFAIK,在这两个函数中,参数都是通过引用传递的,在这两个函数中,我们可以在主程序中更改@array的元素。
改变元素,是的。但是,在 func(@array)
的情况下,sub无法对数组进行其他更改(截断,推送,弹出,切片,将引用传递给还有其他的东西,甚至不知道它)。
我会避免使用术语通过引用传递,因为该机制与Perl的引用完全不同。它不会超载:)在子文件中, @_
的元素的开始时会传递给传递给子元素的元素。
I think I have misunderstood some aspects of argument passing to functions in Perl. What's the difference between func(\@array)
and func(@array)
?
AFAIK, in both functions, arguments are passed by reference and in both functions we can change the elements of @array
in the main program. So what's the difference? When should we use which?
@array = (1,2,3);
func(@array);
func(\@array);
sub func {
...
}
Also, how do I imitate pass-by-value in Perl? Is using @_
the only way?
AFAIK, in both functions, arguments are passed by reference and in both functions we can change the elements of @array in the main program.
"change the elements of", yes. However, in the func(@array)
case, the sub has no means to make other changes to the array (truncating it, pushing, popping, slicing, passing a reference to something else, even undef'ing it).
I would avoid using the term "passed by reference", since the mechanism is completely different than Perl's references. It is less overloaded :) to say that in the sub, @_
's elements start off aliased to the elements passed to the sub.
这篇关于将数组传递给Perl中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!