我试图了解分配子例程的结果是否会导致复制该数据。
sub maketext { 'text' };
my $foo = maketext();
my $foo_ref = \$foo;
my $bar_ref = \maketext();
在上面的例子中,$foo_ref
的创建会比$bar_ref
的创建多一份吗?
我如何让自己相信它们的等价或不等价?
最佳答案
数据复制似乎发生了
sub maketext {
my $text = 'text';
say \$text;
return $text;
}
my $bar_ref = \maketext();
say $bar_ref;
打印出来
SCALAR(0x11f5818) SCALAR(0x11cfa68)
The addresses of data created in the sub and of what $bar_ref
points to are not the same.
On the face of it, as the function returns the data has to be copied, and the reference to that is taken.
The other possibility would be that the reference to the original data is kept even as it goes out of scope, like it happens in closures. However, here the function returns first and its return is then manipulated. So I don't see how any mechanism would know what is done with data, so the data is duly copied.
You are creating an anonymous scalar reference, but out of the function return.
A way to create a reference to a scalar without having the corresponding variable around is
my $scalar_ref = \do { my $var };
或使用 do {\my $var }
,或者在您的情况下使用 sub
sub anon_scalar_ref {
# ...
return \my $var;
}
但是,我看不出你有什么用。也许你想做
sub maketext {
# ... define $text ...
return \$text;
}
当您将 this 的返回值分配给变量时,不会制作额外的数据副本,因为它是返回的引用。
关于perl - 分配子程序的结果是否会导致数据副本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41179399/