chomp
seems to be able to change the value of a variable not passed by reference; that is, the syntax is chomp $var
instead of chomp \$var
.
How is this possible? How can I imitate this behavior in a function?
chomp
:
my $var="foo\n";
chomp $var;
print $var
mychomp
:
my $var="foo\n";
mychomp(\$var);
print $var;
sub mychomp {
my $ref=shift;
$$ref=~s/\s+$//;
}
Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in.
When you pass an argument by reference, you pass a pointer to the value in memory. The function operates on the argument. When a function changes the value of an argument passed by reference, the original value changes. When you pass an argument by value, you pass a copy of the value in memory.
Pass by Value: The method parameter values are copied to another variable and then the copied object is passed, that's why it's called pass by value. Pass by Reference: An alias or reference to the actual parameter is passed to the method, that's why it's called pass by reference.
Passing by ValueExpressions, constants, system variables, and subscripted variable references are passed by value. This means that the actual value of any of these items, rather than the location in memory is passed to functions and procedures.
All Perl parameters are "passed by reference"; more accurately, the contents of @_
are aliases for the actual parameters
Observe
use strict;
use warnings;
use 5.010;
my $s = 'abc';
upper_case($s);
say $s;
sub upper_case {
$_[0] =~ tr/a-z/A-Z/;
}
ABC
Note that calling this function with a data literal, such as
upper_case('def')
will generate the fatal error
Modification of a read-only value attempted
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