Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Using a log object in another object without passing it as a parameter

by thezip (Vicar)
on Aug 08, 2008 at 02:42 UTC ( #703038=perlquestion: print w/ replies, xml ) Need Help??
thezip has asked for the wisdom of the Perl Monks concerning the following question:

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.

Comment on Using a log object in another object without passing it as a parameter
Select or Download Code
Re: Using a log object in another object without passing it as a parameter
by pc88mxer (Vicar) on Aug 08, 2008 at 02:54 UTC
    You need to use the Singleton pattern. Something like:
    package Log; my $instance; ... sub get_logger { unless ($instance) { $instance = ...; # create the Log instance here # another option is to throw an exception } $instance; }

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://703038]
Approved by EvanK
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (12)
As of 2015-07-07 10:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (88 votes), past polls