2013-10-29 86 views
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?

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

始终:'使用严格的;使用警告;'。 – Kenosis

回答

2

只需使用输出文件句柄LOGOUT以及print。您也需要在实际打印之前打开输出文件句柄。

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); 

注:建议不要使用裸字的文件句柄。使用魔法<diamond operator>

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; 
+0

我刚刚开始,我试着让我的代码尽可能简单。感谢您的帮助,但您提供的建议不会创建包含记录的输出文件。 – LMN0321

+0

@ LMN0321您是否收到任何错误?否则它应该工作。 – jkshah

+0

不,我没有得到一个错误,它只是没有创建一个输出文件。我添加了一个额外的行,似乎工作,我不知道它的正确的语法,或者如果它实际上写入文件。 – LMN0321

2

另一种解决方案:我宁愿上述片的代码重写如下

#!/usr/bin/env perl 

use strict; use warnings; 

while (<>) { 
    print; 
} 

用法在一个

$ perl script.pl <input.txt> output.txt 
相关问题