Reputation: 40718
Is there any advantage of returning a reference to the string instead of the string itself when using the e
modifier?
For example:
use strict;
use warnings;
my $str1 = my $str2 = "aa bb cc";
$str1 =~ s/\s(bb)\s/${func1($1)}/e;
$str2 =~ s/\s(bb)\s/func2($1)/e;
sub func1 {
my ($name) = @_;
my $str = "A large string";
return \$str;
}
sub func2 {
my ($name) = @_;
my $str = "A large string";
return $str;
}
I am thinking about the case when the returned string is quite large. Will it be more efficient to use a reference?
Upvotes: 2
Views: 58
Reputation: 385506
Only benchmarking will tell, but it looks like it.
Returning a scalar usually copies it.
$ perl -MDevel::Peek -e'
sub f { my $x = 'abc'; Dump($x); $x } Dump(f());
' 2>&1 | grep -Po 'PV = \K\S*'
0x275d5f0
0x276e270
But not when :lvalue
is used.
$ perl -MDevel::Peek -e'
sub f :lvalue { my $x = 'abc'; Dump($x); $x } Dump(f());
' 2>&1 | grep -Po 'PV = \K\S*'
0x220bd00
0x220bd00
5.20 introduced copy-on-write strings, so both scalars ($x
and the returned one) share the same string buffer until you change one (forcing a copy then).
$ perl -MDevel::Peek -e'
sub f { my $x = 'abc'; Dump($x); $x } Dump(f());
' 2>&1 | grep -Po 'PV = \K\S*'
0xda4780
0xda4780
Upvotes: 2