in reply to How to capture STDOUT/STDERR of a function

Perl has the warn function as a shortcut for print STDERR, so here is a different approach which uses a __WARN__ handler:
use strict; use warnings; $SIG{'__WARN__'} = \&whandler; my ($Errors); warn "Going to call foo()\n"; foo(); print "\nErrors:\n$Errors"; sub foo { # this could be a loop that takes some time to finish. warn "Something to worry about\n"; warn "Something else to worry about\n"; bar(); } sub bar { warn "Darn it.\n" } sub whandler { my $msg = shift; my $caller = (caller(1))[3] || ''; if($caller eq 'main::foo') { $Errors .= $msg; } else { warn $msg } }
Here only calls to warn made directly by foo() will be stored.