#!/usr/local/bin/perl -w use strict; package DelayPrint; sub TIEHANDLE { my $var = ''; bless \$var, shift; } sub PRINT { my $ref = shift; $$ref .= join( (defined $, ? $, : ''), @_) . (defined $\ ? $\ : ''); } sub PRINTF { my $ref = shift; my $fmt = shift; $$ref .= sprintf($fmt, @_); } # flush: an additional function that returns the contents of the buffer # called via the object returned by tie() sub flush { my $ref = shift; my $text = $$ref; $$ref = ''; return $text; } package main; my $fh = tie *STDOUT, 'DelayPrint'; # tie STDOUT print "Hello world\n"; # print through the tied filehandle my $text = $fh->flush(); # get the text that was printed undef $fh; # erase the reference, untie *STDOUT; # untie the filehandle print $text; # print the text for real