Say I have a Parent and a Child classes. I can modify only Child class.
Parent class has some print
's in it.
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;
In my Child class I have a method to print content into log files.
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;
Question: Is there some way to "catch" the stream of those prints from Child class and log that content using the log
method?
Here is the pl file I'm using to try.
#!/usr/bin/perl
use strict;
use warnings;
use Child;
my $child = Child->new;
$child->talk;
$child->talkToLog;
It prints this in console:
Hello world Bye world Hello world Bye world
You need something like this:
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;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments