Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print into two files at once?

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?

like image 644
CheeseConQueso Avatar asked Mar 22 '11 13:03

CheeseConQueso


1 Answers

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.

like image 183
Brian Roach Avatar answered Nov 04 '22 09:11

Brian Roach