Reputation: 29
How to write the output of a subroutine to file?
my $logfile="C:/Test/report_p3.txt";
open(my $tt, ">",$logfile) or die "Can not open file";
foreach (@files)
{
if (($_ ne ".") && ($_ ne ".."))
{
&getinfo($logdir."/".$_);
print $tt &getinfo; #Here, I wanna pass the output to the handler
}
}
close $tt;
on standard output, &getinfo prints correctly the output.
Upvotes: 0
Views: 1616
Reputation: 1963
Is it really necesssary, that the subroutine, whose output you want to pass actually prints something?
Usually you should simply make your sub return a string and have the caller decide where to output it.
my $logfile="C:/Test/report_p3.txt";
open(my $tt, ">",$logfile) or die "Can not open file";
sub get_log {
return "some text to log";
}
sub log_write {
my $log_fh = shift;
print $log_fh get_log() . "\n";
}
log_write($tt); # prints to file handle from $tt
log_write(STDOUT); # prints to STDOUT
Upvotes: 2
Reputation: 2100
Open a filehandle that outputs into a variable, and select it.
After that all output going into STDOUT will be caught in the variable.
Here is an example:
sub output {
print "test\n";
}
my $out;
open VAROUT, '>', \$out;
select VAROUT;
output();
select STDOUT;
printf "output: %s\n", $out;
Upvotes: 4