为什么Perl正则表达式捕获组在“打印”和算术运算之间的行为不同?

在 Perl (v5.30.0) 中,正则表达式被评估为捕获,当用作参数时print()

# Simplified example; the real case has more text, and the capture covers only part of it.

echo $'1n2n3' | perl -ne 'print /(.)/'
# 123

这对于文本提取非常有用。我想利用算术运算的相同便利,但这并不能按预期工作:

# Attempt to compute a sum of the int value of the captures
#
echo $'1n2n3' | perl -ne '$tot += /(.)/; END { print $tot }'
# 3

# Attempt to print twice the int value of each capture
#
echo $'1n2n3' | perl -ne 'print(/(.)/ * 2)'
# 222

使用捕获变量工作:

echo $'1n2n3' | perl -ne 'if (/(.)/) { $tot += $1 }; END { print $tot }'
# 6

但是,我很好奇为什么会发生这种情况,以及是否可以以任何方式使用以前的更紧凑的形式来对捕获的值执行算术运算。

回答

那是因为m//在标量上下文中返回 1 表示成功(请参阅perlop)。您可以强制列表上下文返回匹配的部分:

echo $'1n2n3' | perl -ne '$tot += (/(.)/)[0]; END { print $tot }'


以上是为什么Perl正则表达式捕获组在“打印”和算术运算之间的行为不同?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>