Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Re: pass by value vs reference and return by value

by Athanasius (Chancellor)
on Oct 27, 2013 at 14:57 UTC ( #1059911=note: print w/replies, xml ) Need Help??

in reply to pass by value vs reference and return by value

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:

foo($x, $y, $z);

then within the body of sub foo the special array variable @_ contains references to the three arguments. In Perl terminology, $_[0] is an alias for $x, $_[1] is an alias for $y, and $_[2] is an alias for $z. This is strictly equivalent to a reference in C++: any changes made to $_[0] 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:

sub foo { my ($p, $q, $r) = @_; ... }

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.

See perlreftut and perlootut.

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1059911]
NodeReaper slips on a banana skin

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (3)
As of 2018-01-18 16:50 GMT
Find Nodes?
    Voting Booth?
    How did you see in the new year?

    Results (213 votes). Check out past polls.