We help IT Professionals succeed at work.

Redirecting STDOUT to a variable

paulj1999
paulj1999 asked
on
3,144 Views
Last Modified: 2010-05-18
Hi,

     There's a nice perl module which I really want to use:

PDF::Reuse

You create a PDF in the following manner (According to the instructions)
prFile(FILENAME)
...lines of code....
prEnd

if you don't add FILENAME, the output goes to STDOUT.  The problem is I need the output in a variable.  How can I redirect STDOUT into a variable?

Thanks
Comment
Watch Question

IT Consultant
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
ozo
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015

Commented:
use Tie::Handle::ToMemory;

Commented:
Commenting on this one.

Sadly it seems quite impossible with this module. Normally, you could use something like IO::Capture::Stdout in this sort of manner:

my $capture = IO::Capture::Stdout->new();
$capture->start();
prFile();
...
prDoc( $template );
prEnd();
$capture->end();
my @lines = $capture->read();
my $pdfData = join('', @lines);

But the way PDF::Reuse opens STDOUT is the open() 'trick' open( FILEHANDLE, ">-"); which seems to mean it opens its own handle to the STDOUT, bypassing perl's handle, so it can't be captured. I'd be happily corrected, but this seems to be the case.

We tried many different methods for capturing STDOUT to variables including:
tie *STDOUT, "IO::Scalar", \$variable;
prFile();
...
prEnd();
untie *STDOUT;

(being careful to capture any errors etc. in an eval, otherwise any graceful output of errors to the browser using, STDOUT, is still being redirected to the variable!)

anyways we couldn't get it working, so our solution was to write the PDF::Reuse PDF to a temporary file, open & slurp the contents, then unlink the temporary file, which is a whole lot of extra work for something that should be simple. I'd love it if you could pass a scalar variable to prFile, or your own FILEHANDLE (which could be a properly captured STDOUT), or even have the generated PDF returned as a string on prEnd. That'd be nice, but that's life. Might email the maintainers when I get a chance.

But good luck anyway.
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.