Re: pass by value vs reference and return by valueby Athanasius (Prior)
|on Oct 27, 2013 at 14:57 UTC||Need Help??|
In C and C++, the default mechanism for passing arguments to a function is pass-by-value. To get pass-by-reference, you need to (in effect) override the default by explicitly either (1) passing a pointer (simulated pass-by-reference) or (2) declaring the function parameter to be a reference (C++ only).
In Perl, it’s the other way around. The default mechanism for passing arguments to a subroutine is pass-by-reference. For example, if you call:
then within the body of sub foo the special array variable @_ contains references to the three arguments. In Perl terminology, $_ is an alias for $x, $_ is an alias for $y, and $_ is an alias for $z. This is strictly equivalent to a reference in C++: any changes made to $_ within sub foo are actually made to $x. The normal Perl idiom is to simulate pass-by-value by beginning the function body like this:
which makes local copies of the subroutine arguments.
Note that in Perl arguments are passed in to @_ as a flat list of scalar values. So if you want to pass in, say, two arrays, and retain their separate identities, you use references: foo(\@array1, \@array2); which are themselves scalars. These work like C pointers (or C++ references). As hippo has explained, Perl objects are also references, so when an object argument is copied within a subroutine, it is only the reference — and not the underlying object — which is copied.
As regards return-by-reference, remember that Perl uses reference-counted garbage collection, so it is safe to create an object within a subroutine and then return it to the caller. And since objects are references, returning an object involves the copying of a single scalar value (the reference) only.
Hope that helps,