Mar*_*cus 1 regex perl text-processing capturing-group
在 Perl (v5.30.0) 中,正则表达式被评估为捕获,当用作参数时print():
# Simplified example; the real case has more text, and the capture covers only part of it.
echo $'1\n2\n3' | perl -ne 'print /(.)/'
# 123
Run Code Online (Sandbox Code Playgroud)
这对于文本提取非常有用。我想利用算术运算的相同便利,但这并不能按预期工作:
# Attempt to compute a sum of the int value of the captures
#
echo $'1\n2\n3' | perl -ne '$tot += /(.)/; END { print $tot }'
# 3
# Attempt to print twice the int value of each capture
#
echo $'1\n2\n3' | perl -ne 'print(/(.)/ * 2)'
# 222
Run Code Online (Sandbox Code Playgroud)
使用捕获变量工作:
echo $'1\n2\n3' | perl -ne 'if (/(.)/) { $tot += $1 }; END { print $tot }'
# 6
Run Code Online (Sandbox Code Playgroud)
但是,我很好奇为什么会发生这种情况,以及是否可以以任何方式使用以前的更紧凑的形式来对捕获的值执行算术运算。
那是因为m//在标量上下文中返回 1 表示成功(请参阅perlop)。您可以强制列表上下文返回匹配的部分:
echo $'1\n2\n3' | perl -ne '$tot += (/(.)/)[0]; END { print $tot }'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
83 次 |
| 最近记录: |