in reply to Re: Re: single instance shared with module
in thread single instance shared with module
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.";
|
|---|