Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Perl 如何在函数参数中区分变量和文字/常量_Perl - Fatal编程技术网

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

Perl 如何在函数参数中区分变量和文字/常量,perl,Perl,在这种情况下,如何识别传递给函数f()的是变量还是文本 如何实现传递的作为常量的检查(见下面的代码) 谢谢大家! 不要这样做。函数的行为应该始终相同。就地修改相当不明显。如果要修改值,请显式请求引用。这使得修改在调用站点上更加可见 如果您确实必须确定参数是否为常量,则可以使用。在内部,每个标量都有一个标志,用于控制是否允许修改。这是为文字设置的。对只读标量的赋值将失败。使用readonly()您可以查询此标志。附议“不要这样做”的建议。非常感谢您,阿蒙!Scalar::Util::readonl

在这种情况下,如何识别传递给函数f()的是变量还是文本

如何实现传递的作为常量的检查(见下面的代码)


谢谢大家!

不要这样做。函数的行为应该始终相同。就地修改相当不明显。如果要修改值,请显式请求引用。这使得修改在调用站点上更加可见


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

附议“不要这样做”的建议。非常感谢您,阿蒙!Scalar::Util::readonly这正是我需要的。除了答案试图解释为什么您不需要它,也不应该需要它之外:(
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!');