使用另一个文件的输入输出到文件

时间:2013-10-29 17:47:01

标签: perl input output

我正在尝试使用其他文件的输入输出到文件。没有键盘输入。

我知道我走在正确的轨道上,我的语法有点偏离。

基本上,我从文件“boot.log”中获取记录,使用模式匹配选择某些记录并将它们输出到名为“bootlog.out”的文件中。我还没有进入模式匹配部分。这就是我的......

open (BOOTLOG, "boot.log") || die "Can't open file named boot.log: $!";

while ($_ = <BOOTLOG>)
{
print $_;
}

open (LOGOUT, ">bootlog.out") || die "Can't create file named bootlog.out: $!\n";

close (LOGOUT) || die "Can't close file named bootlog.out: $!\n";

close (BOOTLOG) || die "Can't close the file named boot.log: $!";

如何将boot.log的内容打印到bootlog.out?

EDIT1

这似乎将输入输出到第二个文件。语法是否正确?

open (BOOTLOG, "boot.log") || die "Can't open file named boot.log: $!";

open (LOGOUT, ">bootlog.txt") || die "Can't create file named bootlog.out: $!\n";

while ($_ = <BOOTLOG>)
{
print $_;
print LOGOUT $_;
}

close (LOGOUT) || die "Can't close file named bootlog.txt: $!\n";

close (BOOTLOG) || die "Can't close the file named boot.log: $!";

2 个答案:

答案 0 :(得分:2)

只需使用输出文件句柄LOGOUTprint。您还需要在实际打印之前打开输出文件句柄。

open (BOOTLOG, "boot.log") || die "Can't open file named boot.log: $!";
open (LOGOUT, ">bootlog.out") || die "Can't create file named bootlog.out: $!\n";
while (<BOOTLOG>)
{
    print LOGOUT $_;
}  
close (LOGOUT);
close (BOOTLOG);

注意:建议不要使用裸字文件句柄。我希望重写上面的代码如下:

use strict;
use warnings;    

open my $fh_boot_log, '<', 'boot.log' or die "Can't open file 'boot.log': $!";
open my $fh_log_out, '>', 'bootlog.out' or die "Can't create file 'bootlog.out': $!\n";
while (<$fh_boot_log>)
{
    print $fh_log_out $_;
}  
close $fh_log_out;
close $fh_boot_log;

答案 1 :(得分:2)

另一种使用魔法<diamond operator>的解决方案:

#!/usr/bin/env perl

use strict; use warnings;

while (<>) {
    print;
}

中的用法:

$ perl script.pl < input.txt > output.txt