Che*_*eso 7 printing perl file syntax-error
我无法让这行代码工作:
for my $fh (FH1, FH2, FH3) { print $fh "whatever\n" }
Run Code Online (Sandbox Code Playgroud)
我在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"; }
Run Code Online (Sandbox Code Playgroud)
我正在使用"Bareword"错误,(fh1, fh2)
因为我正在使用它strict
.我也注意到他们;
在示例中缺少了一个,所以我猜测除此之外可能会有更多错误.
一次打印到两个文件的正确语法是什么?
Bri*_*ach 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"; }
Run Code Online (Sandbox Code Playgroud)
请注意,我没有使用裸字.在过去,你会使用:
open(FH1, ">$stat_file");
...
for my $fh (FH1, FH2) { print $fh "whatever\n"; }
Run Code Online (Sandbox Code Playgroud)
但现代的方法是前者.
我只想使用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;
Run Code Online (Sandbox Code Playgroud)
运行上述程序会导致:
This is file number one foobar
This is file number two foobar
我建议阅读整个perldoc文件以获得更高级的用法.