http://www.perlmonks.org?node_id=30264

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question: (files)

Is it possible to write to 2 files, eg. print LOGFILE,TEMP 'hello'?

Originally posted as a Categorized Question.

  • Comment on Is it possible to write to 2 files, eg. print LOGFILE,TEMP 'hello'?

Replies are listed 'Best First'.
Re: Is it possible to write to 2 files, eg. print LOGFILE,TEMP 'hello'?
by nardo (Friar) on Aug 30, 2000 at 19:12 UTC
    multiprint("hello\n", LOGFILE, TEMP); sub multiprint { my $text = shift; for my $fh (@_) { print $fh $text; } }
Re: Is it possible to write to 2 files, eg. print LOGFILE,TEMP 'hello'?
by belg4mit (Prior) on Sep 26, 2003 at 14:58 UTC
      how about
      print $_ "hello" for (\*TEMP, \*LOGFILE);

      Carter's compass: I know I'm on the right track when by deleting something, I'm adding functionality.

Re: Is it possible to write to 2 files, eg. print LOGFILE,TEMP 'hello'?
by davido (Cardinal) on Sep 26, 2003 at 07:50 UTC
    From the Perl Cookbook.

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

    And then an example adapted from the same section is:

    my ($file1, $file2, $file3) = qw/this.out that.out other.out/; my $fh; open $fh, "| tee $file1 $file2 $file3 > /dev/null" or die $!; print $fh "data\n" or die $!; close $fh or die $!;

    Of course this will only be of value to those whos operating systems support tee (Linux / Unix, for example). The reason for the redirection to /dev/null is because tee typically copies its output on STDOUT. If you don't want that extra copy you redirect it to /dev/null (the garbage can).