我无法让这行代码正常工作:
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"; }
但现代方法是前者。
关于perl - 如何一次打印成两个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5392115/