假设我有一个父类和一个子类。 我只能修改 Child 类。
父类中有一些print
。
package Parent;
use strict;
use warnings;
sub new
{
my $class = shift;
my $self = {};
bless $self, $class;
return $self;
}
sub sayHello{
my $self = shift;
print "Hello world\n";
}
sub sayBye{
my $self = shift;
print "Bye world\n";
}
1;
在我的 Child 类中,我有一个将内容打印到日志文件中的方法。
package Child;
use strict;
use warnings;
use parent 'Parent';
sub new
{
my $class = shift;
my $self = $class->SUPER::new();
return $self;
}
sub talk{
my $self = shift;
$self->sayHello;
$self->sayBye;
}
sub talkToLog{
my $self = shift;
my $logName = 'file.log';
$self->log($logName, $self->sayHello); # Here's my best (not working) try
$self->log($logName, $self->sayBye);
}
sub log{
my $self = shift;
my $filename = shift;
my $string = shift;
open(my $fh, ">>", $filename) || die "Couldn't open file $filename: $!";
print $fh $string;
close $fh;
return;
}
1;
问题:是否有某种方法可以“捕获”来自 Child 类的这些打印流并使用 log
方法记录该内容?
这是我用来尝试的 pl 文件。
#!/usr/bin/perl
use strict;
use warnings;
use Child;
my $child = Child->new;
$child->talk;
$child->talkToLog;
它在控制台中打印:
Hello world Bye world Hello world Bye world
最佳答案
你需要这样的东西:
sub talkToLog{
my $self = shift;
my $logName = 'file.log';
my $output = '';
open TOOUTPUT, '>', \$output or die "Can't open TOOUTPUT: $!";
select TOOUTPUT;
$self->sayHello;
$self->log($logName, $output);
$output = '';
$self->sayBye;
$self->log($logName, $output);
select STDOUT;
}
关于perl - 从其他类方法重定向打印流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46298535/