Book HomePerl CookbookSearch this book

7.18. Printing to Many Filehandles Simultaneously

Problem

You need to output the same data to several different filehandles.

Solution

If you want to do it without forking, write a foreach loop that iterates across the filehandles:

foreach $filehandle (@FILEHANDLES) {
    print $filehandle $stuff_to_print;
}

If you don't mind forking, open a filehandle that's a pipe to a tee program:

open(MANY, "| tee file1 file2 file3 > /dev/null")   or die $!;
print MANY "data\n"                                 or die $!;
close(MANY)                                         or die $!;

Discussion

A filehandle sends output to one file or program only. To duplicate output to several places, you must call print multiple times or make a filehandle connected to a program like tee, which distributes its input elsewhere. If you use the first option, it's probably easiest to put the filehandles in a list or array and loop through them:

# `use strict' complains about this one:
for $fh ('FH1', 'FH2', 'FH3')   { print $fh "whatever\n" }
# but not this one:
for $fh (*FH1, *FH2, *FH3)      { print $fh "whatever\n" }

However, if your system supports the tee program, or if you've installed the Perl version from Recipe 8.19, you may open a pipe to tee and let it do the work of copying the file to several places. Remember that tee normally also copies its output to STDOUT, so you must redirect tee 's standard output to /dev/null if you don't want an extra copy:

open (FH, "| tee file1 file2 file3 >/dev/null");
print FH "whatever\n";

You could even redirect your own STDOUT to the tee process, and then you're able to use a regular print directly:

# make STDOUT go to three files, plus original STDOUT
open (STDOUT, "| tee file1 file2 file3") or die "Teeing off: $!\n";
print "whatever\n"                       or die "Writing: $!\n";
close(STDOUT)                            or die "Closing: $!\n";

See Also

The print function in perlfunc (1) and in Chapter 3 of Programming Perl; the "Typeglobs and Filehandles" sections of Chapter 2 of Programming Perl and Chapter 2 of Programming Perl; we use this technique in Recipe 8.19 and Recipe 13.15


Previous: 7.17. Caching Open Output FilehandlesPerl CookbookNext: 7.19. Opening and Closing File Descriptors by Number
7.17. Caching Open Output FilehandlesBook Index7.19. Opening and Closing File Descriptors by Number

Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.