如何一次打印成两个文件?

时间:2011-03-22 13:34:54

标签: perl printing file syntax-error

我无法让这行代码工作:

for my $fh (FH1, FH2, FH3) { print $fh "whatever\n" }

我在perldoc找到了它,但它对我不起作用。

我到目前为止的代码是:

my $archive_dir = '/some/cheesy/dir/';
my ($stat_file,$stat_file2) = ($archive_dir."file1.txt",$archive_dir."file2.txt");
my ($fh1,$fh2);

for my $fh (fh1, fh2) { print $fh "whatever\n"; }

我在(fh1, fh2)部分收到“Bareword”错误,因为我正在使用strict。我也注意到他们在示例中错过了;,所以我猜测除此之外可能会有更多错误。

一次打印到两个文件的正确语法是什么?

5 个答案:

答案 0 :(得分:17)

您尚未打开文件。

my ($fh1,$fh2);
open($fh1, ">", $stat_file) or die "Couldn't open $stat_file: $!";
open($fh2, ">", $stat_file2) or die "Couldn't open $stat_file2: $!";

for my $fh ($fh1, $fh2) { print $fh "whatever\n"; }

请注意,我使用裸字。在过去,你会使用:

open(FH1, ">$stat_file");
...
for my $fh (FH1, FH2) { print $fh "whatever\n"; }

但现代方法是前者。

答案 1 :(得分:7)

我只会使用IO::Tee

use strict;
use warnings;
use autodie; # open will now die on failure
use IO::Tee;

open my $fh1, '>', 'file1';
open FH2, '>', 'file2';

my $both = IO::Tee->new( $fh1, \*FH2 );

print {$both} 'This is file number ';

print {$fh1} 'one';
print FH2    'two';

print {$both} "\n";
print {$both} "foobar\n";

$both->close;

运行上述程序会导致:

文件1

This is file number one
foobar

file2的

This is file number two
foobar

我建议您阅读整个perldoc file以获得更高级的用法。

答案 2 :(得分:4)

这看起来是正确的,它只是在Perl中常见的是使用裸字作为文件句柄,但现在建议使用普通标量。

因此,请确保您确实打开了文件,然后将(fh1, fh2)部分替换为实际文件句柄(可能是($fh1, $fh2)或其他内容)

答案 3 :(得分:0)

首先需要打开文件才能获得有效的文件句柄

open (MYFILEA, $stat_file);
open (MYFILEB, $stat_file2);
for my $fh ( \*MYFILEA, \*MYFILEB ) { print $fh "whatever\n" } 
close (MYFILEA);
close (MYFILEB); 

答案 4 :(得分:0)

另一个版本基于Brian的回答:

open(my $fh1, ">", $stat_file) or die "Couldn't open $stat_file!";
open(my $fh2, ">", $stat_file2) or die "Couldn't open $stat_file2!";
for ($fh1, $fh2) { print $_ "whatever\n"; }
相关问题