Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is it that chomp is able to change the value of a variable not passed by reference?

Tags:

perl

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+$//;
}
like image 738
n.r. Avatar asked Jul 18 '15 15:07

n.r.


People also ask

Does pass by reference change value?

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.

How are arguments passed by value or by reference?

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.

What is pass by value and pass by reference?

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.

What is used to pass the value of a variable to a function?

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.


1 Answers

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/;
}

output

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
like image 197
Borodin Avatar answered Nov 02 '22 23:11

Borodin