0

我正在尝试使用来自另一个文件的输入输出到一个文件。没有键盘输入。

我知道我走在正确的轨道上,我的语法有点不对劲。

基本上,我从文件“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?

编辑1

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

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: $!";
4

2 回答 2

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;
于 2013-10-29T17:52:12.167 回答
2

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

#!/usr/bin/env perl

use strict; use warnings;

while (<>) {
    print;
}

中的用法:

$ perl script.pl < input.txt > output.txt
于 2013-10-29T18:27:26.037 回答