我在使这一行代码正常工作时遇到麻烦:

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。我还注意到在示例中他们缺少;,因此我猜测除此之外可能还会有其他错误。
一次打印到两个文件的正确语法是什么?

最佳答案

您尚未打开文件。

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"; }

但是现代方法是前者。

10-06 04:49