So while attempting to patch a bug recently, a fellow hacker told me that since the value of the string passed to the subroutine (method) might be quite large, accessing it via $_[1] would avoid the memory copy. However, I thought that any value passed to a subroutine was copied to @_ in the first place? so in the below example is the memory copied twice? or am I wrong about the copy made when passing to the method?
sub foo {
my $self = shift
$_[0] # access $str in @_ directly
my ( $str ) = @_; # makes another copy of @_
}
sub bar {
my $self = shift;
my $str = 'something very large';
$self->foo( $str ); #copies $str to the @_ of foo
}
This is why I suggested to the author allowing pass by a scalar ref, which will avoid a copy (other than the reference itself ) when passing to the method itself. To reiterate: does passing a value to a subroutine mean the value gets copied into @_?
According to http://perldoc.perl.org/perlsub.html (emphasis is mine):
By my reading, this seems to indicate that, by default, no copy occurs into
@_.Though I will admit that the language used is a little obtuse.