程序中遇到一个问题,一个引用变量传入函数中,如果赋值一个新的引用,则外部引用没有改变,如果更改引用内容,则变量随之改变,做个记录,下次注意。
如下为示例:
sub test1{
my $x = shift;
$x = {left=>undef, right=>undef, key=>123, parent=>undef,};
}
sub test2{
my $x = shift;
$x->{key} = 123;
}
$t = {left=>undef, right=>undef, key=>undef, parent=>undef,};;
use Data::Dumper ;
test1($t);
print Dumper $t;
test2($t);
print Dumper $t;$VAR1 = {
'left' => undef,
'parent' => undef,
'right' => undef,
'key' => undef
};
$VAR1 = {
'left' => undef,
'parent' => undef,
'right' => undef,
'key' => 123
};
本文通过两个Perl函数示例探讨了引用变量在函数内的行为差异。当在函数内部为传入的引用赋新值时,原始变量不受影响;而修改引用所指向的内容时,外部变量随之变化。文章提供了具体代码实例来说明这一现象。
5458

被折叠的 条评论
为什么被折叠?



