【问题标题】:Print how many substitutions took place in a Perl s///g?打印在 Perl s///g 中发生了多少次替换?
【发布时间】:2019-08-09 03:23:53
【问题描述】:

我使用了网络搜索,找到了类似标题的问题How many substitutions took place in a Perl s///g? 并尝试使用它来打印号码但未能成功。

我的初始代码是

perl -0777 -i.original -pe 's-\r\n-\n-igs' test.txt

当我尝试时

perl -0777 -i.original -pe "$c=s-\r\n-\n-igs;say qq'$c'" test.txt

当我尝试时,我什么也没得到 - 没有输出也没有替换

perl -0777 -i.original -pe '$c=s-\r\n-\n-igs;print qq($c\n)' test.txt

(print 与我之前使用的其他单行代码类似)我在标准输出中得到了空字符串,但 454847 添加为文件的开头(以及适当的替换)。

我知道 =~ 在我的情况下不需要 (What does =~ do in Perl?),那么我的代码有什么问题?如何打印更换次数?

【问题讨论】:

  • @ikegami,archname='x86_64-msys-thread-multi'。这是 Win7 上的 Git bash。我做了一些替换,现在想看看在替换命令后有哪些与文本编辑器通知的相同。

标签: regex perl


【解决方案1】:

由于-i,默认输出句柄不是STDOUT,而是输出文件。要打印到 STDOUT,您需要明确地这样做。

如果使用cmd shell,

perl -0777pe"CORE::say STDOUT s/\r//g" -i.original test.txt

如果使用sh 或类似名称,

perl -0777pe'CORE::say STDOUT s/\r//g' -i.original test.txt

注意事项:

  • s/// 比 s--- 更惯用
  • /i 在这里没用。
  • /s 在这里没用。
  • 检查换行没有意义。 s/\r//g 和 s/\r\n/\n/g 一样好用。
  • 使用变量进行计数是有意义的,尤其是在使用say 而不是print 时。
  • 出于向后兼容性的原因,必须使用CORE::say 而不是say,除非使用use feature qw( say ); 或等效项。
  • s/\r\n/\n/g 和 s/\r//g 都不能与 Perl 的 Windows 版本一起使用,并且在 Perl 的 Windows 版本上使用 -i 时无法执行您想要的操作。但是,您使用的是 Perl 的 unix 版本(因为 MSYS 是一个 unix 仿真环境),所以这不是问题。

【讨论】:

  • 我想补充一下我在网上找到的知识:The say function behaves just like the print function, except that it appends a newline at the end of its arguments.,只是固定代码是perl -0777 -i.original -pe '$c=s-\r\n-\n-igs;CORE::print STDOUT qq($c\n)' test.txt 。 p.s.我最初使用 ` 作为分隔符,但 stackoverflow 使用它来表示代码。哦,我没有猜到添加到文件中的数字是我的输出!
  • 无需使用CORE::print 代替print。 say 是后来添加到 Perl 中的,因此必须使用 CORE::say 以实现向后兼容性,除非使用 use feature qw( say ); 或类似的。将此添加到我的答案中。
  • 我在这里很困惑。为什么你在回答中写了CORE?
  • 这在之前的评论和我的回答中都有解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-10
  • 2017-06-02
  • 1970-01-01
  • 1970-01-01
  • 2021-06-24
  • 2011-01-19
相关资源
最近更新 更多