Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Redirect Subroutine Output

by goeb (Pilgrim)
on Aug 26, 2009 at 15:54 UTC ( #791374=note: print w/ replies, xml ) Need Help??


in reply to Redirect Subroutine Output

You could write the sub the following way:

use warnings; use strict; sub print_to { print {$_[0]} $_[1]; } print_to (*STDOUT, "test stdout"); print_to (*STDERR, "test stderr");


Comment on Re: Redirect Subroutine Output
Download Code
Re^2: Redirect Subroutine Output
by spickles (Scribe) on Aug 26, 2009 at 18:08 UTC
    goeb -

    Why do I get the error 'scalar found where operator expected' if I omit the braces around the $_[0]? What are the braces doing and why aren't they required around the second element?

    Regards,
    Scott
      From the docs for print:
      Note that if you're storing FILEHANDLEs in an array, or if you're using any other expression more complex than a scalar variable to retrieve it, you will have to use a block returning the filehandle value instead:
      I believe the braces define a block of code, and I believe $_[0] qualifies as an 'expression more complex than a scalar variable'. If you refactor the sub like this, then the braces around the FILEHANDLE are not needed:
      use warnings; use strict; sub print_to { my ($fh, $str) = @_; print $fh $str; } print_to (*STDOUT, "test stdout"); print_to (*STDERR, "test stderr");

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://791374]
help
Chatterbox?
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: (7)
As of 2015-07-07 04:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (87 votes), past polls