in reply to Is it possible to do pass by reference in Perl?

*Only* scalars can be passed to a sub as parameters, and they can *only* be passed by reference. If you modify @_, the actual variable passed in gets modified! @_ is really a list of aliases to the argument list.

Try it:

sub foo { $_[0] = 17 } my $x=0; foo $x; print "$x\n"
And foo @x does what you'd expect given the aliasing.

Of course, the usual course of action is to copy them into my variables. Which is why it's perceived as call by value.

Replies are listed 'Best First'.
Passing a reference by value is somewhat equivalent to call by reference
by stefp (Vicar) on Sep 24, 2001 at 15:55 UTC
    It is only possible to pass scalars by reference to a sub.

    Parameters are passed by value in Perl. But we have an operator, the backslash, that returns reference to any variable (scalar or composite). So the net result is that we have a mechanism to pass parameter by reference.

    Admittedly, this not very clean, because the formal parameter is declared as a scalar even if it is a reference to a non scalar. I guess that was the point that tried to convey the sentence: It is only possible to pass scalars by reference to a sub.

    sub foo { my $a = shift; push @$a, "foobar"; } my @a = (); foo \@a; # passing a value that is a reference to @a print $a[1]; # prints "foobar"
    tilly messages me: another example of how to pass arrays by reference is by using prototypes. Unlike using \ in user code, that is transparent.. So Perl has call by reference after all (even if it was quite a late addition?).

    -- stefp