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) 输出
1
xxxbbcc
我想同时做这两件事,而不必先匹配:替换并知道替换的数量。显然,as///g 不会返回标量上下文中的替换数量——与 m//g 对匹配项所做的不同。这可能吗?如果是,怎么办?
perlre、perlvar 和 perlop 没有提供任何帮助(或者我只是找不到它)。
Small example:
perl -e '$s="aaabbcc";$c=()=$s=~/a/g;print"$c\n$s\n"'
(m//g) outputs
3
aaabbcc
whereas perl -e '$s="aaabbcc";$c=()=$s=~s/a/x/g;print"$c\n$s\n"'
(s///g) outputs
1
xxxbbcc
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 and perlop provided no help (or I just couldn't find it).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
s///
确实返回标量上下文中进行的替换数。来自 perlop (添加了强调):您的问题是您没有在标量上下文中调用
s///
。您在列表上下文中调用它,然后在标量上下文中评估分配(到空列表)。标量上下文中的列表赋值返回表达式右侧生成的元素数。由于s///
返回单个值(在列表和标量上下文中),因此即使s///
没有执行任何操作,元素数量也始终为 1 。要在标量上下文中调用
s///
,请省略=()=
伪运算符。s///
does return the number of substitutions made in scalar context. From perlop (emphasis added):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. Sinces///
returns a single value (in both list and scalar context) the number of elements is always one even if thes///
didn't do anything.To call
s///
in scalar context, omit the=()=
pseudo-operator.