打印 Perl s///g 中发生了多少次替换? [英] Print how many substitutions took place in a Perl s///g?

查看:61
本文介绍了打印 Perl s///g 中发生了多少次替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了网络搜索,发现了类似标题的问题 Perl s///g 中发生了多少次替换? 并尝试使用它来打印数字但未能成功.

I've used web search, found similarly titled question How many substitutions took place in a Perl s///g? and tried to use it to print the number but have not been able to succeed.

我的初始代码是

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

当我尝试时,我一无所获 - 没有输出也没有替换

I got nothing - no output and no replacements, when I tried

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

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

(print similar to other one-liners I used before) I got empty string in standard output but 454847 added as the beginning of file (and proper replacements).

我知道在我的情况下不需要 =~(什么=~ 在 Perl 中是做什么的?),那么我的代码有什么问题?如何打印替换次数?

I understand =~ is not needed in my case (What does =~ do in Perl?), so what is wrong with my code? How to print number of replacements made?

推荐答案

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

Because of -i, the default output handle isn't STDOUT but the output file. To print to STDOUT, you'll need to do so explicitly.

如果使用 cmd shell,

If using the cmd shell,

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

如果使用 sh 或类似的,

If using sh or similar,

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/gs/\r//g 都不能用于 Perl 的 Windows 版本,而且没有办法在 Windows 版本的 Perl 上使用 -i 时做你想做的事.但是,您使用的是 Perl 的 unix 版本(因为 MSYS 是一个 unix 仿真环境),所以这不是问题.
  • s/// is more idiomatic than s---
  • /i is useless here.
  • /s is useless here.
  • There no point in checking for Line Feeds. s/\r//g will work just as fine as s/\r\n/\n/g.
  • There's point in using a variable for the count, especially if using say instead of print.
  • One must use CORE::say instead of say for backwards compatibility reasons unless use feature qw( say ); or equivalent is used.
  • Neither s/\r\n/\n/g nor s/\r//g will work with a Windows build of Perl, and there's no way to do what you want when using -i on a Windows build of Perl. However, you are using a unix build of Perl (since MSYS is a unix emulation environment), so it's not an issue.

这篇关于打印 Perl s///g 中发生了多少次替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆