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
- the module dups STDERR into its own filehandle called ERROR, and
- the module defines a format called ERROR for printing to the filehandle.
Since the ERROR filehandle is defined at module use time, it is necessary to do STDERR munging in a BEGIN block, thusly:
open(my $olderr, '>&', STDERR) or die "Cannot dup 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?).
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.)
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
Outside of code tags, you may need to use entities for some characters:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
| & || & |
| < || < |
| > || > |
| [ || [ |
| ] || ] ||