如何在函数参数中区分变量与文字/常量

时间:2018-02-20 17:19:24

标签: perl

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

如何实现pass_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!');

谢谢!

1 个答案:

答案 0 :(得分:8)

不要这样做。该函数应始终表现相同。就地修改是非常明显的。如果要修改值,请明确要求引用。这使得修改在呼叫站点更加明显。

如果您确实需要确定参数是否为常量,则可以使用readonly() from Scalar::Util。在内部,每个标量都有一个标志,用于控制是否允许修改。这是为文字设置的。对只读标量的分配将失败。使用readonly(),您可以查询此标记。