Subroutine arguments in Perl are passed by reference, unless they are in the signature. This means that the members of the @_
array inside the sub are just aliases to the actual arguments. In the following example, $text
in the main program is left modified after the subroutine call because $_[0]
inside the sub is actually just a different name for the same variable. The second invocation throws an error because a string literal is not a variable and therefore can't be modified.
use feature 'say';
sub edit {
$_[0] =~ s/world/sub/;
}
my $text = "Hello, world!";
edit($text);
say $text; # Hello, sub!
edit("Hello, world!"); # Error: Modification of a read-only value attempted
To avoid clobbering your caller's variables it is therefore important to copy @_
to locally scoped variables (my ...
) as described under "Creating subroutines".