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

我无法让这行代码工作:
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”错误,因为我使用严格.我也注意到他们错过了一个;在这个例子中,所以我猜可能会有更多的错误.

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

解决方法

您尚未打开文件.
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. 如何去重 #!/usr/bin/perl use strict; my %hash; while(...
最近写了一个perl脚本,实现的功能是将表格中其中两列的数据...
表的数据字典格式如下:如果手动写MySQL建表语句,确认麻烦,...
巡检类工作经常会出具日报,最近在原有日报的基础上又新增了...
在实际生产环境中,常常需要从后台日志中截取报文,报文的形...
最近写的一个perl程序,通过关键词匹配统计其出现的频率,让...