How can I print to a variable instead of a file, in Perl?
perl, printing
Solution
You can treat a scalar variable as a filehandle by `open`ing it:
open my $fh, '>', \$variable or die "Can't open variable: $!";
print $fh "Treat this filehandle like any other\n";
You can even map stdout or stderr to a scalar:
close STDOUT;
open STDOUT, '>', \$variable or die "Can't open STDOUT: $!";
If you want to split your output or set up a config file to do "interesting" things with your logging, you are better off with Log4Perl as others have suggested.
Problem
How can I print to a variable with Perl? I've been working on a program for a while which logs its iterative progress in a highly verbose fashion... ``` print $loghandle $some_message; ``` However, I'd like to also selectively print some of the messages to a different file. Naturally, I could sprinkle the code with... ``` print $loghandle $some_message print $otherloghandle $some_message ``` Or rewrite the whole business into a function. Blah. What I want to do is do some magic when I open the $loghandle so that when I'm `print`'ing, I'm actually just doing a `sprintf`ish operation against a variable(call it `$current_iteration`), so that when I get down to a decision point I can do something like this... ``` print $real_log_file $current_iteration; print $other_real_log_file $current_iteration if($condition); ``` I'm fairly sure I've seen something like this somewhere, but I have no idea where it is or where to look. edit: File::Tee solves this problem to some extent on *nix, but I run on Windows.