Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Nested redirect for STDERR to a string buffer within a perl program

by ikegami (Patriarch)
on Apr 30, 2025 at 16:22 UTC ( [id://11164862]=note: print w/replies, xml ) Need Help??


in reply to Nested redirect for STDERR to a string buffer within a perl program

Have you considered using Capture::Tiny?

  • Comment on Re: Nested redirect for STDERR to a string buffer within a perl program

Replies are listed 'Best First'.
Re^2: Nested redirect for STDERR to a string buffer within a perl program
by Anonymous Monk on May 01, 2025 at 15:11 UTC
    Thank you ikegami, I tried Capture::Tiny and it allows to nest wrapping of redirections for STDERR. Example code:
    #!/usr/bin/env perl use strict; use warnings; use Capture::Tiny ':all'; sub innerAction { print STDERR "FIRST CAPTURE\n"; # to innerbuffer, works } sub handleInner { print STDERR "INNER before capture\n"; my ($innerBuffer, @results) = capture_stderr { innerAction(); }; print STDERR "INNER past restore\n"; # above goes to console or the outerbuffer, # it fails for outerbuffer when called from handleOuter chomp $innerBuffer; my $no=1; foreach my $line (split("\n", $innerBuffer)) { print "BUFFER (inner): $no; #>>$line<\n"; $no++; } } sub outerAction { print STDERR "OUTER before call\n"; # to outerbuffer handleInner(); print STDERR "OUTER past call\n"; # to outerbuffer } sub handleOuter { print STDERR "OUTER BEFORE CAPTURE\n"; my ($outerBuffer, @resuts) = capture_stderr {outerAction();}; print STDERR "OUTER PAST RESTORE\n"; chomp $outerBuffer; my $no=1; foreach my $line (split("\n", $outerBuffer)) { print "BUFFER (outer): $no; #>>$line<\n"; $no++; } } handleInner(); print "################################# \n"; handleOuter();
    Produces this output which shows that the outer redirect continues when the inner redirect is done.
    INNER before capture INNER after restore INNER past restore BUFFER (inner): 1; #>>FIRST CAPTURE< ################################# OUTER BEFORE CAPTURE BUFFER (inner): 1; #>>FIRST CAPTURE< OUTER PAST RESTORE BUFFER (outer): 1; #>>OUTER before call< BUFFER (outer): 2; #>>INNER before capture< BUFFER (outer): 3; #>>INNER past restore< BUFFER (outer): 4; #>>OUTER past call<
    BTW: Account creation is really a pain here. And only 10 letters for passwords?

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11164862]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (3)
As of 2025-07-14 14:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.