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.

In reply to Using a log object in another object without passing it as a parameter by thezip

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.