in reply to Re: How to pass array literal through pass by reference
in thread How to pass array literal through pass by reference

Thanks for the reply, please make me understand, does using the "[" brackets will pass the parameter by ref?
  • Comment on Re^2: How to pass array literal through pass by reference

Replies are listed 'Best First'.
Re^3: How to pass array literal through pass by reference
by kennethk (Abbot) on Mar 16, 2009 at 20:29 UTC

    Please read the link I provided you (perlref) as it discusses anonymous arrays. A look through perlreftut would also likely do you some good.

    No matter what you do in Perl, arguments are always passed as an explicit list of values, just like in C. In passing by reference, you are really passing a pointer to an array. You can generate such a pointer with the \@array syntax that you used in your example code (also discussed in perlref). The syntax [1, 2, 3] returns a pointer to an array (1,2,3). That array has no symbolic representation within your namespace, and is thus "anonymous".

    So the short answer is that the syntax

    WriteToFile( ["abc", "23343"] );

    passes a reference to an array containing ("abc", "23343") to the subroutine WriteToFile.

Re^3: How to pass array literal through pass by reference
by kyle (Abbot) on Mar 16, 2009 at 21:08 UTC

    If you think of "pass by reference" in C terms, Perl subs always receive their arguments in a "pass by reference" fashion. Arguments come in the array, @_, and the elements of that array are what we call aliases to the original values. If you modify an element of that array, you are modifying the original value.

    my $so_called_constant = 'unmodified'; print "constant: $so_called_constant\n"; make_modified( $so_called_constant ); print "constant: $so_called_constant\n"; make_modified( 'literal' ); sub make_modified { $_ = 'modified' for @_ } __END__ constant: unmodified constant: modified Modification of a read-only value attempted

    Note that there are other places where these aliases appear naturally, and you can create them deliberately.

    What we call a "reference", a C programmer would probably call a "pointer". The brackets in "[ 1, 2, 3 ]" create a reference to an array that doesn't have a name. It's exactly like the reference you get from "\@triplet" except that there isn't a variable that holds the array whence came the reference.