Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
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 ( [id://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.

Replies are listed 'Best First'.
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
Domain Nodelet?
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?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (6)
As of 2024-04-18 07:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found