in reply to Re^2: Redirect Subroutine Output
in thread Redirect Subroutine Output

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

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

Replies are listed 'Best First'.
Re^4: Redirect Subroutine Output
by spickles (Scribe) on Aug 26, 2009 at 18:23 UTC
    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 :
      Sounds like you want ambrus's 3rd solution
      # Open log file once open(MYFILE, '>>', $qfn) or die("Cannot open file $qfn for appending: $!\n"); ... print_to($to_file ? *MYFILE : *STDOUT, $str);

      Better yet, use a lexical

      open(my $MYFILE, '>>', $qfn) or die("Cannot open file $qfn for appending: $!\n"); ... print_to($to_file ? $MYFILE : *STDOUT, $str);

      Finally, if you want to reopen the file every time you call print_to,

      my $MYFILE; if ($to_file) { open($MYFILE, '>>', $qfn) or die("Cannot open file $qfn for appending: $!\n"); print_to($to_file ? $MYFILE : *STDOUT, $str); } else { $MYFILE = *STDOUT; } print_to($MYFILE, $str);