I'm wondering why Perl has ability to pass argument by reference to function? I know that neither Python, nor Ruby doesn't have such feature.
Pass-by-references is more efficient than pass-by-value, because it does not copy the arguments. The formal parameter is an alias for the argument. When the called function read or write the formal parameter, it is actually read or write the argument itself.
Perl always passes by reference.
Pass by value sends a copy of the data stored in the variable you specify, and pass by reference sends a direct link to the variable itself. So if you pass a variable by reference and then change the variable inside the block you passed it into, the original variable will be changed.
It's useful to distinguish one thing from another.
(1) Passing arguments to a subroutine by reference. This is useful in Perl because the language passes all arguments to a subroutine as an undifferentiated list of values. Without the ability to passed data structures by reference, the designer of a function taking two lists, for example, would not be able to keep the lists separate. In addition, if the data structures are large, passing them by reference can provide a performance gain.
process_two_lists( @x, @y); # Can't distinguish the lists.
process_two_lists(\@x, \@y); # Can.
Because Python and Ruby are designed differently, they don't require this distinction in how arguments are passed. A similar method in Python or Ruby would receive two distinct arguments (two objects representing lists x
and y
).
(2) Perl's behavior whereby @_
serves as an alias to the passed arguments, allowing the subroutine to modify data as perceived by the caller.
sub add_ten_to_me {
$_[0] += 10;
}
my $x = 1;
add_ten_to_me($x);
say $x; # 11 Amazing!
Python and Ruby can do this type of thing as well; however, there are some qualifications. Python distinguishes between mutable and immutable objects. If you pass something mutable to a Python method (a list, for example), the method is able to modify the data structure. So a Python version of process_two_lists
would be able to modify both x
and y
. However, a function receiving immutable objects (an integer, for example) would not. Thus, a direct Python analog of add_ten_to_me
would not work. [I believe that similar points could be made about Ruby, but I'm less familiar with the details at this point.]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With