in reply to How to capture STDOUT/STDERR of a function
Here only calls to warn made directly by foo() will be stored.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 } }
|
|---|