Perl s///g 中发生了多少次替换? [英] How many substitutions took place in a Perl s///g?
问题描述
小例子:
perl -e '$s="aaabbcc";$c=()=$s=~/a/g;print"$c\n$s\n"'
(m//g) 输出
3
aaabbcc
而 perl -e '$s="aaabbcc";$c=()=$s=~s/a/x/g;print"$c\n$s\n"'代码> (s///g) 输出
whereas perl -e '$s="aaabbcc";$c=()=$s=~s/a/x/g;print"$c\n$s\n"'
(s///g) outputs
1
xxxbbcc
我想同时做这两件事,而不必先匹配:替换并知道替换的次数.显然, s///g 不会返回标量上下文中的替换次数——与 m//g 在匹配时所做的不同.这可能吗?如果是,如何?
I'd like to do both things at once without having to match first: substitute and know the number of substitutions. Obviously a s///g does not return the number of substitutions in scalar context--unlike m//g does with matches. Is this possible? If yes, how?
perlre、perlvar 和 perlop 没有提供任何帮助(或者我就是找不到).
perlre, perlvar and perlop provided no help (or I just couldn't find it).
推荐答案
s///
确实返回在标量上下文中进行的替换次数.来自 perlop(强调):
s///
does return the number of substitutions made in scalar context. From perlop (emphasis added):
s/PATTERN/REPLACEMENT/msixpogce
在字符串中搜索模式,如果找到,则替换该模式带有替换文本的模式,返回数量替换.否则它返回 false(特别是,空字符串).
s/PATTERN/REPLACEMENT/msixpogce
Searches a string for a pattern, and if found, replaces that pattern with the replacement text and returns the number of substitutions made. Otherwise it returns false (specifically, the empty string).
你的问题是你没有在标量上下文中调用 s///
.您在列表上下文中调用它,然后在标量上下文中评估 赋值(到一个空列表).标量上下文中的列表赋值返回表达式右侧生成的元素数.由于 s///
返回单个值(在列表和标量上下文中),即使 s///
没有做任何事情,元素的数量也总是一.
Your problem is that you didn't call s///
in scalar context. You called it in list context and then evaluated the assignment (to an empty list) in scalar context. A list assignment in scalar context returns the number of elements produced by the right-hand side of the expression. Since s///
returns a single value (in both list and scalar context) the number of elements is always one even if the s///
didn't do anything.
perl -E "$s='aaabbcc'; $c=()=$s=~s/x/y/g; say qq'$c-$s'" # prints "1-aaabbcc"
要在标量上下文中调用 s///
,请省略 =()=
伪运算符.
To call s///
in scalar context, omit the =()=
pseudo-operator.
perl -E "$s='aaabbcc'; $c=$s=~s/a/x/g; say qq'$c-$s'" # prints "3-xxxbbcc"
这篇关于Perl s///g 中发生了多少次替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!