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.";
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|