Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Redirect Subroutine Output

by ikegami (Patriarch)
on Aug 26, 2009 at 17:06 UTC ( [id://791395]=note: print w/replies, xml ) Need Help??


in reply to Redirect Subroutine Output

Better solution:
my $out_fh; if ($to_file) { open($out_fh, '>', ...) or die(...); } else { $out_fh = \*STDOUT; } ... print $out_fh "blah\n";

You can also change the default handle:

if ($to_file) { open(my $out_fh, '>', ...) or die(...); select($out_fh); } ... print "blah\n";

Replies are listed 'Best First'.
Re^2: Redirect Subroutine Output
by spickles (Scribe) on Aug 26, 2009 at 17:30 UTC
    This is why I LOVE this website...so many options! Thanks to everyone that responded. The quickest and most direct route for me is to store to a concatenated string and then print that string to either STDOUT or MYFILE depending on how I call a print function.

      print that string to either STDOUT or MYFILE depending on how I call a print function.

      print { $to_file ? *MYFILE : *STDOUT } $str;
        ikegami -

        How do I define *MYFILE? I've been doing it using open(MYFILE,'>>out.txt'); But to write to that file, it has to be opened, written to, and then closed. So I'm not sure how to define MYFILE prior to calling the print_to() function. Would it now be a file handle, and pass something like $fh to the subroutine? I don't know what words to use to look up more about your method of passing variables using the ? and :

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (6)
As of 2024-04-19 14:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found