I'm having trouble getting this line of code to work:
for my $fh (FH1, FH2, FH3) { print $fh "whatever\n" }
I found it at perldoc but it doesn't work for me.
The code I have so far is:
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"; }
I'm getting "Bareword" errors on the (fh1, fh2)
part because I'm using strict
. I also noticed they were missing a ;
in the example, so I'm guessing there might be some more errors aside from that.
What's the correct syntax for printing to two files at once?
You haven't opened the files.
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"; }
Notice that I'm not using barewords. In the olden days, you would have used:
open(FH1, ">$stat_file");
...
for my $fh (FH1, FH2) { print $fh "whatever\n"; }
but the modern approach is the former.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With