vrk has asked for the wisdom of the Perl Monks concerning the following question:
Dear monks,
I would like to capture the error output of Parse::RecDescent to a variable instead of printing it to STDERR. There does not seem to be any way of doing this easily; there is no documentation for it, and viewing the source code reveals that
Since the ERROR filehandle is defined at module use time, it is necessary to do STDERR munging in a BEGIN block, thusly:
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;
However, fine as it is though hairy, this will not produce any content in $ParseError, which will stay undefined. If I replace the STDERR re-open with an opening of a file, say
open(STDERR, '>', '/tmp/error') or die $!;
I do get the error strings in /tmp/error!
Is the cause of the problem the use of format in Parse::RecDescent, or some other subtle things I'm missing? An issue with buffering? Or is the approach fundamentally flawed? I guess I could open an anonymous temporary file somehow, redirect STDERR to that, then read in the contents of the file, but surely there is a better way. (This is on Perl 5.8.8 on Linux, x86_64, if that's relevant.)
--
print "Just Another Perl Adept\n";
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: How to grab Parse::RecDescent error output in a variable?
by ikegami (Patriarch) on Sep 12, 2008 at 10:20 UTC | |
by vrk (Chaplain) on Sep 15, 2008 at 08:07 UTC | |
by ikegami (Patriarch) on Sep 15, 2008 at 12:00 UTC | |
by tfrayner (Curate) on Sep 15, 2008 at 13:09 UTC | |
by Pic (Scribe) on Sep 15, 2008 at 17:12 UTC | |
by vrk (Chaplain) on Sep 17, 2008 at 08:21 UTC | |
Re: How to grab Parse::RecDescent error output in a variable?
by vrk (Chaplain) on Sep 12, 2008 at 08:44 UTC |