我有一個文本文件,下面的線爲例添加標題到一個文本文件中的Perl
This is line
This is line with test
This is ine with 2test
This is line 2
This is line 3
This is line with 3test
This is line 4
This is line with 4test
現在我想一個代碼來更改文本文件,如下所示:
Lines with test
This is line with test
This is ine with 2test
This is line with 3test
This is line with 4test
Lines without test
This is line
This is line 2
This is line 3
This is line 4
我正在使用下面的代碼。我假設我的代碼會打印每行的標題,但由於某些錯誤,我無法執行代碼。 你能幫我嗎?
#!/usr/bin/perl
use strict;
use warnings;
open(FH, '<filetest.txt');
my @queues = <FH>;
close(FH);
open(OFH,'>testfile.txt');
my $name;
foreach $name(@queues)
{
if($name =~ 'test')
{
print OFH "Lines with test\n";
print OFH $1;
}
else{
print OFH "Lines without test\n";
print OFH $1;
}
close(OFH);
}
注:我糾正了錯誤刪除的語法錯誤,但仍然沒有什麼被寫入到文件TESTFILE.TXT
「由於一些錯誤」 - 語法錯誤,要準確。提示:錯誤的來源可能會在報告錯誤的位置之前發生。還要注意,'#'開始一個行註釋,並且這個正則表達式必須使用某種類型的正則表達式,比如'/ foo /'。但即使在那之後,你的代碼也存在各種bug。 (1)一次讀取和寫入同一個文件是行不通的。 (2)您對'open'使用陳舊的語法,並且不執行任何錯誤檢查。 (3)'$ 1'不會被填充。使用'$ _'。 (4)輸出*每行*的標題。相反,首先將這些行放入數組中。 (...) – amon