perl 解析插入新行和 ^M

perl parsing inserting new line and ^M

我正在尝试使用以下逻辑使用 perl 修改文件中的一些字符串..

open FILE1, "< /tmp/sam.dsl" //In read mode
open FILE2, "> /tmp/sam2.dsl" // Open in write mode

while(<FILE1>)
if($_=s/string/found/g)
push FILE2, $_...

我可以更改内容,但是当我读取文件时它里面有 ^M..

我的数据文件格式如下

name 'SAMPLE'

我想将其更改为

name 'SAMPLE2'

目前我的代码更改为

name 'SAMPLE2
'

创建一个新行然后进行替换。

我是否需要使用任何其他模式打开文件写入..?

我的猜测是,您正在使用某个 windows 上的 linux 文件。在 dos 兼容的机器上,Perl 在读取之后和写入之前自动将 \n 转换为 \r\n。要摆脱这种行为,您可以在文件句柄上使用 binmode <FILE>,但它会将您的文件句柄设置为 "raw binary mode"。如果你想使用一些其他层(如 :utf8:encoding(utf-8))未启用,并且你可能想自己设置它们,如果你正在处理字符数据。您还可以使用 CPAN 中的 PerlIO::eol 模块。

考虑查看这些文档页面:

  • PerlIO 了解 Perl-IO 的工作原理。
  • open 为一个程序设置图层的编译指示(不是函数)。
  • binmode 您可能要考虑的功能。

我的建议,但我无法测试(周围没有 Windows),将使用以下内容:

open my $outfile, '<:encoding(utf-8)', "filename" or die "error opening: $!";
binmode $outfile, join '', grep {$_ ne ':crlf'} PerlIO::get_layers($outfile)
  or die "error setting output:\n $!"

while(<$infile>){
  s/match/replacement/g;
  print $outfile $_;
}