dpenny has asked for the wisdom of the Perl Monks concerning the following question: (subroutines)

I'm kind of a newbie, but, I've read all the docs, I've written machine language interfacing to Fortran and C. I've written a simple interpreter in Fortran and again in C. And I stll cannot figure out if Perl passes by value or by reference. An eariler posting talks about "implicit" reference. There is no such thing as implicit at the code level. The docs talk about "turning call-by-reference into call-by-value", hugh, how can this be? Either Perl pushes the value of args (be they scalors or arrays) onto a stack (ie, copies the whole thingy), or it pushes a pointer to the item onto the stack. There is NO OTHER WAY. What is the truth? Why do Perl docs seem so confusing, even uncertain? Can someone explain clearly in a few words? Thanks.

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: Subroutine args by-value vs. by-ref
by wog (Curate) on Aug 24, 2002 at 06:02 UTC

    The implict reference is not a hard reference, as perlref speaks of, but an aliasing that occurs. For example:

    sub x { $_[0] = "in x"; } my $foo = "outside"; x($foo);
    ... will set $foo to "in x". The thing in @_ has become an alias for $foo. However, you won't get this behavior if you explictly copy the value out of @_, as in:
    sub x { my($foo) = @_; $foo = "in x"; } my $foo = "outside"; x($foo);
    When you copy the value, you are not working with an alias to the thing passed in, but you a working with a copy, bringing you the pass-by-value semantics that are probably more intutitive to you.

Re: Subroutine args by-value vs. by-ref
by Anonymous Monk on Aug 24, 2002 at 01:40 UTC
    All your previous experience is confusing you.

    Read perldata, perlsyn, perlref and perlsub (if perlsub exists).

    There are no pointers in perl, there are only scalar's hashes's and array's, and references. Some might say there are also lists, and they're right.

    subroutines get arguments via the magical @_ variable, meaning every time you say Foo(1,2,3), inside of sub Foo, the @_ array will contain 1,2 and 3 as it's value.

    That's pass-by-value.

    my @Arra = ( 1, 2, 3, 4 ); PassByReference(\@Arra); sub PassByReference { die "@_"; }
    Here are some more examples.
    use Data::Dumper; DIE(1..10); DIE(1,2,3,4,5,6,,8,9); DIE( [ 1..10 ] ); DIE( { 1..10 } ); my @ARRAY = 1..10; my %HASH = @ARRAY; DIE( @ARRAY ); DIE( %HASH ); DIE( \@ARRAY ); DIE( \%HASH ); DIE( @ARRAY, \%HASH ); DIE( \@ARRAY, \%HASH ); DIE( \@ARRAY, %HASH ); DIE( \&DIE ); ¨ DIE(); sub DIE { print Dumper(@_) };