#!/usr/bin/perl # save original STDERR open my $saved_stderr, ">&STDERR"; # create a pipe, which we'll use to read STDERR local(*RH, *WH); pipe RH, WH; # connect the writing side of the pipe to STDERR, with # STDERR being (and remaining) fileno 2 (!) open STDERR, ">&WH" or die "open: $!"; # debug: verify that fileno(STDERR) really is 2 printf "fileno(STDERR): %d\n", fileno(STDERR); # execute external command my $out = `perl -e "print 'hello world'; die('this is a fatal error')"`; my $ret = $?; # close WH to avoid buffering issues (pipes are buffered) close WH; # read output (one line) # (todo: fix so it doesn't block when there's nothing to read!) my $err = ; close RH; # restore original STDERR open STDERR, ">&", $saved_stderr or die "open: $!"; print "return value: $ret\n"; print "captured stdout: $out\n"; print "captured stderr: $err\n";