perl - 分配子程序的结果是否会导致数据副本?

标签 perl reference pass-by-value

我试图了解分配子例程的结果是否会导致复制该数据。

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/

相关文章:

c++ - 在这种情况下,您如何正确使用 ifstream 的引用?错误 C2248

c++ - 按引用传递然后复制和按值传递在功能上是否不同?

perl - 在递归 ssh 命令中引用 bash 和 perl

perl - 按返回类型重载函数

c# - 为什么不能将 Type 用作常量值?

java - Java参数引用和原始引用(不是对象)如何相同?

Java - 按值传递示例

linux - 以相反顺序打印由点分隔的字符串

python - HTTPS GET 请求并读取 JSON 回复

c# - 如何在 Microsoft Azure 中的同一解决方案中引用项目