简体   繁体   中英

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?

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.

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;

Running the above program results in:

file1

This is file number one
foobar

file2

This is file number two
foobar

I would recommend reading the whole perldoc file for more advanced usage.

That looks about right, it's just that it used to be common in Perl to use barewords as file handles, but nowadays it's recommended to use normal scalars.

So make sure that you actually have the files open, then just substitute the (fh1, fh2) part with the actual file handles (which would be ($fh1, $fh2) or something)

You first need to open the file in order to get valid filehandles

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

another version based off of 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"; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM