【发布时间】:2014-02-05 02:12:37
【问题描述】:
我有一个文本文件,其中包含以下几行作为示例
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/。但即使在那之后,您的代码仍然存在各种错误。 (1) 一次读取和写入同一个文件是行不通的。 (2) 您对open使用过时的语法,并且不执行任何错误检查。 (3)$1不会被填充。使用$_。 (4) 你输出 each 行的标题。相反,首先将行放入数组中。 (…)
标签: perl filehandle