[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Any way to Tee in MacPerl?



Wade Williams <wwilliam@cisco.com> wrote:
>I'm writing a program that's eventually going to end up on UNIX and I need
>to write to two files (STDOUT and a file) simultaneously.
>
>I know that on UNIX, I can do:
>
>open(FILE, "| tee file2");
>
>print FILE "some text\n";

There isn't anything macperl specific about this solution, but I hope
I can help out anyway.

How about using the tied filehandle interface to create a module that
writes to all the filehandles it is given as arguments.


package TeeHandle;

use FileHandle;

# Ties a glob to a filehandle, all the optional arguments are the actual
# filehandles to write to when our tied filehandle is written to.
sub TIEHANDLE {
  my $class = shift;
  my $self = { handles => [ @_ ] };
  bless $self, $class;
  return $self;
}

# print to all of our filehandles.
# note this ignores the return value of print. This is unlike the 
# built in print function, but more like its common usage (where the
# return value is ignored.) Mostly just laziness on my part.
sub PRINT {
  my $self = shift;
  my @args = @_;
  my $handle;
  for $handle(@{$self->{handles}}) {
    $handle->print(@args);
  }
}

# turn a call to printf into one call to sprintf() followed by a
# print.

sub PRINTF {
  my $self = shift;
  my $format = shift;

  $self->PRINT( sprintf $format, @_ );
}

1;

And to use the TeeHandle module, do something like this:

#!/usr/bin/perl
use TeeHandle;
use FileHandle;

my $out = FileHandle->new('>output.txt') or die;

tie *TEE, TeeHandle, *STDOUT, $out;

print TEE "This is a test\n";
printf TEE "And another %s\n", 'test';
-- 
Andrew Langmead

***** Want to unsubscribe from this list?
***** Send mail with body "unsubscribe" to mac-perl-request@iis.ee.ethz.ch