Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Answer: Is it possible to do pass by reference in Perl?

( #149478=categorized answer: print w/ replies, xml ) Need Help??

Q&A > subroutines > Is it possible to do pass by reference in Perl? contributed by Russ

One might argue that Perl always does Pass-By-Reference, but protects us from ourselves.

@_ holds the arguments passed to a subroutine, and it is common idiom to see something like:

sub mySub{ my $Arg = shift; } sub mySub2{ my ($Arg) = @_; }
Why is that? Why don't we just use the @_ array directly?

First, there is the laudable goal of more readable code, which is sufficient reason, in itself, to rename variables away from cryptic things like $_[3]. But really, we copy values out of @_ because (from the man page) "its elements are aliases for the actual scalar parameters."

In short, this means that if you modify an element of @_ in your subroutine, you are also modifying the original argument. This is almost never the expected behavior! Further, if the argument is not updatable (like a literal value, or a constant), your program will die with an error like "Modification of a read-only value attempted."

Consider:

sub test{ $_[0] = 'New Value'; } my $Var = 'Hi there'; print "$Var\n"; test ($Var); print "$Var\n";
will print out:
Hi there New Value
So, yes, you can do pass-by-reference in Perl, even without backslashes; but it is almost always better (some would leave out the "almost" in this statement) to make your caller explicitly pass you a reference if you intend to modify a value.

Comment on Answer: Is it possible to do pass by reference in Perl?
Select or Download Code
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (8)
As of 2015-07-31 01:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (274 votes), past polls