Well, as I said, you can pass an instance of A (which is an object) to B and B can then call your the object's WriteLog method. You probably would want to pass the instance to B's constructor and allow B to contain the instance of A so it could use it wherever it needed it.

If A is a class implementing a log file and WriteLog() is a method to write an entry to, say, an open logfile managed by an instance of A and you need to write to the same log file from both the main and B packages, then this approach probably makes sense. Just make sure you document that B uses an instance of A to write to a log.

Update: Here is some example code:

#!/usr/bin/perl -w use strict; package A; sub new { my $class = shift; my ($fh) = @_; bless { FH => $fh }; } sub WriteLog { my $self = shift; my $fh = $self->{FH}; print $fh "[",scalar localtime,"] ",@_,"\n" } package B; sub new { my $class = shift; my ($logobj) = @_; bless { A => $logobj }; # B contains instance of A. } sub Foo { my $self = shift; my $log = $self->{A}; $log->WriteLog("B::Foo wrote this!"); } package main; my $A = A->new(\*STDOUT); my $B = B->new($A); # Pass instance of A to B's constructor. $A->WriteLog("main wrote this!"); # main uses instance of A. $B->Foo(); # B also uses it.
-sauoq
"My two cents aren't worth a dime.";

In reply to Re: Re: Re: single instance shared with module by sauoq
in thread single instance shared with module by Jaap

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.