Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Re: how to control/redirect print()

by smile4me (Beadle)
on Apr 04, 2011 at 18:43 UTC ( #897384=note: print w/replies, xml ) Need Help??

in reply to how to control/redirect print()

So, listening to what GrandFather, Marshall, and others have said. Here's the refactored code:

use 5.010; use strict; use warnings; my ($fh, $str); open ($fh, '>>', \$str) or die "$!"; my $oldSTDOUT = select $fh; $str .= qq[first line: \n]; say q[can we control the print from a sub? ]; sample( qw(1 2 3 ) ); $str .= sample( qw(4 5 6 ) ); say q[ well... ]; select $oldSTDOUT; close $fh; print_now( $str ); sub print_now { my $txt = shift; $txt =~ s/e/E/g; say "txt: $txt"; } sub sample { print 'in sample(): ', @_, "\n"; } __END__ ## output txt: first linE: can wE control thE print from a sub? in samplE(): 123 in samplE(): 456 1 wEll... ## the '1' from sample(456)

Lessons learned:

  • open in append mode so we can add to the $str.
  • anything going to STDOUT is redirected to the variable
  • the legacy subroutine's print is appended to the $str when called inline, but
  • the return value of the print is appended to the str when called in concatenation (scalar mode, terminology?)

Problem Solved!

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (6)
As of 2021-06-12 18:38 GMT
Find Nodes?
    Voting Booth?
    What does the "s" stand for in "perls"? (Whence perls)

    Results (53 votes). Check out past polls.