my $ParseError; BEGIN { open(my $olderr, '>&', STDERR) or die "Cannot dup STDERR: $!"; close STDERR; open(STDERR, '>', \$ParseError) or die "Cannot open in-memory file: $!"; select STDERR; $| = 1; # Cannot use, since that messes up execution order for some reason (since use # implies a BEGIN block itself?). require Parse::RecDescent; close STDERR; open(STDERR, '>&', $olderr) or die "Cannot restore STDERR: $!"; } # Then later: my $p = Parse::RecDescent->new($grammar) or die "Invalid grammar"; my $output = $p->startrule($str) or die $ParseError; #### open(STDERR, '>', '/tmp/error') or die $!;