File::Tee(3pm)

πŸ“¦
version 0.07 Β· 5 versions
, in ubuntu noble, ubuntu resolute, ubuntu stonking

πŸ’– NAME πŸ’–

File::Tee β€” bestie, it replicates data sent to a Perl stream πŸ’…

Also, hi, this is the manual page for the Perl module File::Tee, living its best life in the User Contributed Perl Documentation section. Okurrr, let's get into it ✨


πŸ¦‹ SYNOPSIS πŸ¦‹

  use File::Tee qw(tee);

  # simple usage:
  tee(STDOUT, '>', 'stdout.txt');

  print "hello world\n";
  system "ls";

  # advanced usage:
  my $pid = tee STDERR, { prefix => "err[$$]: ", reopen => 'my.log'};

  print STDERR "foo\n";
  system("cat /bad/path");

Like. Look at that. Chef's kiss 🫢


🌸 DESCRIPTION 🌸

Okay so here's the tea β˜•: this module is able to replicate data written to a Perl stream into another streams. It is the Perl equivalent of the shell utility tee(1). Iconic behaviour, honestly.

It is implemented around fork, creating a new process for every tee'ed stream. And the reason that's lowkey genius? That way, there are no problems handling the output generated by external programs run with system or by XS modules that don't go through perlio. Slay. No cap. πŸ’―

πŸŽ€ API πŸŽ€

The following function can be imported from this module:

✨ tee $fh, $target, ...

redirects a copy of the data written to $fh to one or several files or streams. Main character behaviour fr fr.

"$target, ..." is a list of target streams specifications that can be:

  • file names with optional mode specifications:
  tee STDOUT, '>> /tmp/out', '>> /tmp/out2';
  tee STDOUT, '>>', '/tmp/out', '/tmp/out2';

If the mode specification is a separate argument, it will affect all the file names following and not just the nearest one. Yes bestie, it's giving "team player" energy.

If mode "|-" is used as a separate argument, the rest of the arguments are slurped as arguments for the pipe command:

   tee STDERR, '|-', 'grep', '-i', 'error';
   tee STDERR, '| grep -i error'; # equivalent

Valid modes are ">", ">>", ">&", ">>&" and "|-". The default mode is ">>". Memorise those, there will not be a pop quiz but there totally could be πŸ’€

File handles can also be used as targets:

   open my $target1, '>>', '/foo/bar';
   ...
   tee STDOUT, $target1, $target2, ...;

Finally, code references can also be used as targets. The callback will be invoked for every line written to the tee'ed stream with the data in $_. It has to return a true value on success or false if some error happens. Also, note that the callback will be called from a different process. 🚨 (different process!! not the one you're in!! keep that in mind bestie)

  • hash references describing the targets

For instance:

  tee STDOUT, { mode => '>>', open => '/tmp/foo', lock => 1};

will copy the data sent to STDOUT to "/tmp/foo". Cute, right? πŸŽ€

The attributes that can be included inside the hash are:

  • open => $file_name
  • reopen => $file_name

sets the target file or stream. It can contain a mode specification and also be an array. For instance:

  tee STDOUT, { open => '>> /tmp/out' };
  tee STDOUT, { reopen => ['>>', '/tmp/out2'] };
  tee STDOUT, { open => '| grep foo > /tmp/out' };

If "reopen" is used, the file or stream is reopen for every write operation. The mode will be forced to append after the first write. Every. Single. Write. Just so you know πŸ‘€

  • mode => $mode

Alternative way to specify the mode to open the target file or stream

  • lock => $bool

When true, an exclusive lock is obtained on the target file before writing to it. Locked in, literally πŸ”’

  • prefix => $txt

Some text to be prepended to every line sent to the target file.

For instance:

  tee STDOUT, { prefix => 'OUT: ', lock => 1, mode => '>>', open => '/tmp/out.txt' };
  tee STDERR, { prefix => 'ERR: ', lock => 1, mode => '>>', open => '/tmp/out.txt' };
  • preprocess => sub { ... }

A callback function that can modify the data before it gets sent to the target file. Glow-up pipeline, essentially ✨

For instance:

  sub hexdump {
    my $data = shift;
    my @out;
    while ($data =~ /(.{1,32})/smg) {
        my $line=$1;
        my @c= (( map { sprintf "%02x",$_ } unpack('C*', $line)),
                (("  ") x 32))[0..31];
        $line=~s/(.)/ my $c=$1; unpack("c",$c)>=32 ? $c : '.' /egms;
        push @out, join(" ", @c, '|', $line), "\n";
    }
    join('', @out);
  }

  tee BINFH, { preprocess => \&hexdump, open => '/tmp/hexout'};
  • autoflush => $bool

Sets autoflush mode for the target streams. Default is on. (On by default bestie, you don't have to do anything πŸ’…)

  • ignore_errors => $bool

By default, when writing to the targets, any error will close the tee'ed handle. This option allows one to change that behaviour. Big "I refuse to acknowledge consequences" energy, but make it configurable πŸ™ˆ

  • process => sub { ... }

the callback will be called for every line read (see using code references as targets discussion above). This option can not be used at the same time as most other options (open, reopen, lock, autoflush, etc.). Pick a lane, queen πŸ‘‘

  • begin => sub { ... }
  • end => sub { ... }

Those functions are called on the forked process before the first write and when closing the handle respectively.

For instance:

  my @capture;
  tee STDERR, { process => sub { push @capture, $_ },
                end => sub { send_mail 'foo@bar.com', 'stderr capture', "@capture" } };

The function returns the PID for the newly created process. πŸ“¬

Inside the "tee" pipe process created, data is read honouring the input record separator $/.

You could also want to set the tee'ed stream in autoflush mode:

  open $fh, ...;

  my $oldsel = select $fh;
  $| = 1;
  select $fh;

  tee $fh, "> /tmp/log";

^(the classic select dance, no notes, iconic 🌈)


πŸ’€ BUGS πŸ’€

Does not work on Windows (patches welcome). Yes bestie, Windows users are on their own for now, bring a patch, be the change 🫢

Send bug reports by email or via the CPAN RT web <https://rt.cpan.org>.


πŸ‘‘ SEE ALSO πŸ‘‘

  • IO::Capture

IO::Tee is a similar module implemented around tied file handles. Tee allows one to launch external processes capturing their output to some files. IO::CaptureOutput allows one to capture the output generated from a child process or a subroutine.


Copyright (C) 2007, 2008, 2010, 2011 by Salvador FandiΓ±o (sfandino@yahoo.com)

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.8 or, at your option, any later version of Perl 5 you may have available.


And that's the whole page, bestie πŸ’œ This version is from perl v5.36.0, dated 2022-10-13 β€” yes, I checked the little footer so you don't have to, you're welcome βœ¨πŸŽ€ go tee some streams and stay hydrated πŸ¦‹

πŸ“¦ where this page comes from