在perl中添加标题到文本文件

时间:2014-01-16 08:57:27

标签: perl filehandle

我有一个文本文件,其中以下行为例

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

3 个答案:

答案 0 :(得分:2)

尝试使用:

#!/usr/bin/perl
use strict;
use warnings;

my $infile = 'filetest.txt';
my $outfile = 'testfile.txt';

# use 3-arg open and if open succeeded
open my $fh_in, '<', $infile or die "Unable to open file '$infile' for reading: $!";

my @with_test;
my @without_test;
while (<$fh_in>) {
    if (/test/) {
        push @with_test, $_;
    } else {
        push @without_test, $_;
    }
}
close $fh_in;

open my $fh_out, '>', $outfile or die "Unable to open file '$outile' for writting: $!";
print $fh_out "Lines with test\n";
print $fh_out @with_test;
print $fh_out "Lines without test\n";
print $fh_out @without_test;

close $fh_out;

答案 1 :(得分:1)

我没有测试过这个。我们的想法是立即将“带测试”行写入文件 “无测试”行存储(在一个名为“without”的数组中),直到程序结束然后写入

#!/usr/bin/perl
use strict;
use warnings;
open(FH, '<filetest.txt');
my @queues = <FH>;
close(FH);
open(OFH,'>testfile.txt');
my $name;
my @without=();
foreach $name(@queues)
{
if($name =~ 'test')
{
  print OFH $name;
}
else{
  push @without, $name;
}
print OFH "\n\nlines without\n";
print OFH @without;

}

答案 2 :(得分:0)

你也应该在阅读文件句柄之前添加local $/。 看一下这个: how to read the whole file. 匹配格式应如下所示:if($somestr =~ /#/)。 并且你不应该关闭循环中的文件句柄。

#!/usr/bin/perl

use strict;
use warnings;
local $/;
open(FH, 'file#.txt');
my $s;
$s = <FH>;
close(FH);
open(FH, '>file#.txt');
my @queues = split(/\n/, $s);
my @arr;
my @arr2;
for($s=0; $s<$#queues+1; $s++)
{

    if($queues[$s] =~ /#/)
    {
        push(@arr, $queues[$s]."\n");
    }
    else
    {
        push(@arr2, $queues[$s]."\n");
    }
}
print FH "lines with #\n";
print FH @arr;
print FH "lines without #\n";
print FH @arr2;