How to print two files at once?

I am having trouble working with this line of code:

for my $fh (FH1, FH2, FH3) { print $fh "whatever\n" } 

I found it on perldoc , but it does not 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 get "Bareword" errors in the (fh1, fh2) because I use strict . I also noticed that this example is missing ; , so I suppose there might be a few more errors in this case.

What is the correct syntax for printing two files at once?

+6
file perl printing syntax-error
source share
5 answers

You did not open 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"; } 

Please note that I do not use just words. In the old days, you would use:

 open(FH1, ">$stat_file"); ... for my $fh (FH1, FH2) { print $fh "whatever\n"; } 

but the modern approach is the first.

+17
source share

I would just use 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; 

Execution of the above program leads to:

file1

  This is file number one
 foobar

file2

  This is file number two
 foobar

I would recommend reading the entire perldoc file for more advanced use.

+5
source share

It looks right, just that in Perl it was usually common to use file descriptors, but regular scalars are currently recommended.

So, make sure the files are actually open, and then just replace the part (fh1, fh2) with the actual file descriptors (it will be ($fh1, $fh2) or something else)

+4
source share

First you need to open the file to get valid file descriptors

 open (MYFILEA, $stat_file); open (MYFILEB, $stat_file2); for my $fh ( \*MYFILEA, \*MYFILEB ) { print $fh "whatever\n" } close (MYFILEA); close (MYFILEB); 
0
source share

another version based on Brian's answer:

 open(my $fh1, ">", $stat_file) or die "Couldn't open $stat_file!"; open(my $fh2, ">", $stat_file2) or die "Couldn't open $stat_file2!"; for ($fh1, $fh2) { print $_ "whatever\n"; } 
0
source share

All Articles