在 perl 文件中写入新行

writing new lines in a file in perl

我有一个目录,我正在其中编辑 XML 文件并将它们转换为常规文本文件,其中 - 如果有不止一行数字,则必须将它们保存在单独的新文件中新行。

例如,如果 XML 文件如下所示:

<![CDATA[335 248 450 305
32 251 188 319
472 245 574 290
]]>  

那么我希望转换后的文件看起来像这样:

Bounding box for object 1 "PAScar" (Xmin, Ymin) - (Xmax, Ymax) : (335, 248) - (450, 305)
Bounding box for object 2 "PAScar" (Xmin, Ymin) - (Xmax, Ymax) : (32, 251) - (188, 319)
Bounding box for object 3 "PAScar" (Xmin, Ymin) - (Xmax, Ymax) : (472, 245) - (574, 290)

这是我代码的相关部分:

if($file =~ /\.xml$/i)
    {   $i += 1;
        open (MYFILE, $file); 
        $newlines = "";
        my $objnum;
        $objnum = 0;
        while (my $row = <MYFILE>) 
        {
            my $line;
            $line = "";
            if($row =~ m/\d+(?:\s+\d+){3}$/)
            {
                $objnum=$objnum+1;
                if($row =~ /CDATA/)
                {
                    my($prefix, $suff, $nums) = split(/\[/, $row);
                    $line = $nums
                }
                else
                {
                    $line = $row;
                }
                my ($x1, $y1, $x2, $y2) = split(" ",$line);
                $newlines = $newlines.'\n'.'Bounding box for object '.$objnum.' "PAScar" (Xmin, Ymin) - (Xmax, Ymax) : ('.$x1.', '.$y1.') - ('.$x2.', '.$y2.')';
            }
        }
        close MYFILE;
        my $tempfile;
        my $newfile;
        $tempfile  = "D:/PATH/temp.txt";
        open (my $tmp, '>>:crlf', $tempfile) or die "** can't  open temp file:( **";
        print $tmp $newlines;
        close $tmp;
        copy $tempfile, $file;
        unlink  $tempfile;

问题是我转换后的文件看起来像这样:

\nBounding box for object 1 "PAScar" (Xmin, Ymin) - (Xmax, Ymax) : (335, 248) - (450, 305)\nBounding box for object 2 "PAScar" (Xmin, Ymin) - (Xmax, Ymax) : (32, 251) - (188, 319)\nBounding box for object 3 "PAScar" (Xmin, Ymin) - (Xmax, Ymax) : (472, 245) - (574, 290)

为什么没有换行符? 我正在运行 windows。我知道这不是 Notepad++ 的问题。它在记事本和写字板中也显示为这样。我尝试使用 \r\n 但这也没有换行。

然后,我不是简单地将 $newlines 打印到新文件中,而是尝试这样做:@lines = split("\n", $newlines); 然后运行 ​​foreach $line (@lines) 循环,我在每次迭代中重新打开文件:

foreach $line (@lines)
        {   open ($tmp, '>>', $tempfile) or die "** can't  open temp file:( **";
            print $tmp $line;
        }

但我得到了相同的结果,除了这次没有 \ns,但所有内容都在同一行。

怎么办?

换行:

$newlines = $newlines.'\n'.'Bounding box for object '.$objnum.' "PAScar" (Xmin, Ymin) - (Xmax, Ymax) : ('.$x1.', '.$y1.') - ('.$x2.', '.$y2.')';

至:

$newlines = $newlines."\n".'Bounding box for object '.$objnum.' "PAScar" (Xmin, Ymin) - (Xmax, Ymax) : ('.$x1.', '.$y1.') - ('.$x2.', '.$y2.')';

即你需要用双引号“\n”而不是单引号“\n”来换行。