Consider the following toy script that uses a home-grown logging module Log, and the module Foo:
#!/usr/bin/perl
use strict;
use warnings;
use Log;
use Foo;
my $log = Log->new( { 'logfile' => 'log.txt', 'caller' => $0 } );
my $foo = Foo->new();
...
# do some stuff
$foo->printNum(5);
And the modules Log and Foo:
package Log;
use strict;
use warnings;
sub new {
my ($class, $args) = @_;
open (my $fh, ">>", $args->{'logfile'}) || die "Oops...\n";
my $self = {
_LOGFILE => $args->{'logfile'},
_CALLER => $args->{'caller'},
_FH => $fh,
};
return bless($self, ref($class) || $class);
}
sub writeError {
my ($self, $msg) = @_;
print $msg, "\n";
}
sub get_logger {
...
# What should this code be to allow the Log->writeError()
# call (below in Foo) to succeed???
...
}
1;
package Foo;
use strict;
use warnings;
use Log;
my $log = Log->get_logger();
sub new {
my $class = shift;
my $self = {};
return bless($self, ref($class) || $class);
}
sub printNum {
my ($self, $num) = @_;
my $correct_num = 4;
if ($num != $correct_num) {
$log->writeError("I got a $num instead of a $correct_num!");
}
}
1;
Is there a way to do this without passing $log as a parameter into Foo?
Your wish is my commandline.