Perl打开文件句柄以追加模式读取

时间:2013-12-25 19:57:40

标签: perl

我有一个文本文件,我必须阅读内容并附加到其中。即制作文件的副本并附加到其中。我写了以下代码

#!/usr/bin/perl
use strict;
use warnings;
my $line;
open FILL, ">> fred"
    or warn "Cannot open : $!";
while(<FILL>){
   # s/^Author:.*/Author: Randal L. Schwartz/;
   # s/^Phone:.*\n//;
   # s/^Date:.*/Date: $date/;
    $line.=$_;
    print $line;
}
select FILL;
print $line;

但它根本不进入while循环,当我在读取模式下打开同一文件的文件句柄并选择附加模式下的文件句柄进行打印时可以正常工作。

输入:

Program name: granite
Author: Gilbert Bates
Company: RockSoft
Department: R&D
Phone: +1 503 555-0095
Date: Tues March 9, 2004
Version: 2.1
Size: 21k
Status: Final beta

输出:

Program name: granite
Author: Gilbert Bates
Company: RockSoft
Department: R&D
Phone: +1 503 555-0095
Date: Tues March 9, 2004
Version: 2.1
Size: 21k
Status: Final beta
Program name: granite
Author: Gilbert Bates
Company: RockSoft
Department: R&D
Phone: +1 503 555-0095
Date: Tues March 9, 2004
Version: 2.1
Size: 21k
Status: Final beta

此程序正常运行

#!/usr/bin/perl
use strict;
use warnings;
my $line;
open FIL, "fred"
    or warn "Cannot open : $!";
open FILL, ">> fred"
    or warn "Cannot open : $!";
while(<FIL>){
   # s/^Author:.*/Author: Randal L. Schwartz/;
   # s/^Phone:.*\n//;
   # s/^Date:.*/Date: $date/;
    $line.=$_;
    print $line;
}
select FILL;
print $line;

它在文件中正确附加,但终端输出为

Program name: granite
Program name: granite
Author: Gilbert Bates
Program name: granite
Author: Gilbert Bates
Company: RockSoft
Program name: granite
Author: Gilbert Bates
Company: RockSoft
Department: R&D
Program name: granite
Author: Gilbert Bates
Company: RockSoft
Department: R&D
Phone: +1 503 555-0095
Program name: granite
Author: Gilbert Bates
Company: RockSoft
Department: R&D
Phone: +1 503 555-0095
Date: Tues March 9, 2004
Program name: granite
Author: Gilbert Bates
Company: RockSoft
Department: R&D
Phone: +1 503 555-0095
Date: Tues March 9, 2004
Version: 2.1
Program name: granite
Author: Gilbert Bates
Company: RockSoft
Department: R&D
Phone: +1 503 555-0095
Date: Tues March 9, 2004
Version: 2.1
Size: 21k
Program name: granite
Author: Gilbert Bates
Company: RockSoft
Department: R&D
Phone: +1 503 555-0095
Date: Tues March 9, 2004
Version: 2.1
Size: 21k
Status: Final beta
Program name: granite
Author: Gilbert Bates
Company: RockSoft
Department: R&D
Phone: +1 503 555-0095
Date: Tues March 9, 2004
Version: 2.1
Size: 21k
Status: Final beta

为什么要打印这么多次?

1 个答案:

答案 0 :(得分:1)

$line是您累积到目前为止读取的所有内容的变量。所以在循环中,你可能想要做

print $_;

或只是

print;

而不是

print $line;

回答原始问题...您需要以读写(追加)模式打开文件。

open FILL, '>>+', 'fred';

(请不要使用open的双参数版本。这是不安全的。)

但是这会将文件指针放在文件的末尾,所以你必须做一个

seek FILL, 0, 0;

在阅读之前。由于您在写作之前阅读,因此无论您是否以附加模式打开文件都没有区别。

您甚至可以在阅读文件后添加另一个seek,但我不确定这是否可以在Unix和Windows上移植。