How many substitutions took place in a Perl s///g?

落爺英雄遲暮 提交于 2019-12-01 15:24:49

s/// does return the number of substitutions made in scalar context. From perlop (emphasis added):

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).

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"

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"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!