It's worth noting that the special variable, "@_" contains aliases to the calling args, not copies of them. Therefore, there is no copy being made here:
sub foo {
return length($_[0]);
}
...because we're acting only on the aliased entity. Similarly, there should be no copy here (assuming the s/// operator doesn't make one):
sub dot_to_underscore {
$_[0] =~ s/\./_/g;
}
my $string = 'hello.world';
print "$string\n";
dot_to_underscore($string);
print "$string\n";
No copy because we acted upon the alised entity, which is the same as acting upon the entity itself. On the other hand, had we unpacked our args by assigning $string to some other variable lexically scoped to the subroutine, done a substitution (probably triggering copy on write), and then returned the string, we have the opportunity to have created at very least one copy.
Copying small strings and simple values such as integers, and even floating point numbers is pretty fast, and for general cases we probably shouldn't care. But for long strings I can see where it would be useful to be aware of what will and will not trigger a buffer copy.
On the other hand, consider this:
sub dot_to_underscore {
my $string = $_[0]; # No copy on 5.20+, but yes, copy under <5.20
+.
$string =~ s/\./_/; # Copy made under 5.20 because of copy-on-wri
+te.
return $string; # No copy under 5.20+ until the *caller* modi
+fies the return string. But yes, the caller will get a copy pre-5.20.
}
|