gpt4 book ai didi

perl - 如何区分函数参数中的变量和文字/常量

转载 作者:行者123 更新时间:2023-12-04 22:46:46 29 4
gpt4 key购买 nike

在这种情况下,如何识别是否有变量或字面量传递给函数 f()?

如何实现passed_as_constant()检查(见下面代码)?

sub f {
my $refStr=\$_[0];
return if passed_as_constant($_[0]) and !defined(wantarray);
substr(${$refStr}, 0, 1)='D';
# return the copy of the string if it was passed
# to the function as constant aka "literally" or if copying was explicitly requested by the left-side context
(passed_as_constant($_[0]) or defined(wantarray)) and return ${$refStr};
}
# Argument was passed literally and function called without left-side context - we may simply "do nothing"
f('Bingo!');

# Argument was passed literally and left-side context is here. We must return a copy of literal/constant
say my $s=f('Bingo!');

# Here we can modify the $s "in-place"
f(my $s='Bingo!');

谢谢!

最佳答案

不要这样做。该功能应始终表现相同。就地修改相当不明显。如果要修改值,请明确要求提供引用。这使得修改在调用站点上更加明显。

如果你真的要判断一个参数是否为常数,你可以使用 readonly() from Scalar::Util .在内部,每个标量都有一个标志来控制是否允许修改。这是为文字设置的。对只读标量的分配将失败。使用 readonly() 可以查询这个标志。

关于perl - 如何区分函数参数中的变量和文字/常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48890828/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com