如何避免 PDL 子程序中的输入修改

How to avoid input modification in PDL subroutines

我想避免使用赋值运算符 .= 修改子程序中的用户输入。

避免这种情况的一种方法是在子例程中执行输入的副本。这是最好的方法吗?还有其他解决方案吗?

use PDL;use strict;
my $a=pdl(1);
f_0($a);print "$a\n";
f_1($a);print "$a\n";
sub f_0{
    my($input)=@_;
    my $x=$input->copy;
    $x.=0;
}
sub f_1{
    my($input)=@_;
    $input.=0;
}

在我的例子中 (perl 5.22.1),执行最后一个脚本会在两行中打印 10f_0 不会就地修改用户输入,而 f_1 会。

根据常见问题 6.17 What happens when I have several references to the same PDL object in different variables :

Piddles behave like Perl references in many respects. So when you say

$a = pdl [0,1,2,3]; $b = $a;   

then both $b and $a point to the same object, e.g. then saying

$b++; 

will not create a copy of the original piddle but just increment in place
[...]
It is important to keep the "reference nature" of piddles in mind when passing piddles into subroutines. If you modify the input piddles you modify the original argument, not a copy of it. This is different from some other array processing languages but makes for very efficient passing of piddles between subroutines. If you do not want to modify the original argument but rather a copy of it just create a copy explicitly...

是的,为避免修改原件,请像您一样创建副本:

my $x = $input->copy;

或者:

my $x = pdl( $input );