tempfoo has asked for the wisdom of the Perl Monks concerning the following question:

What would be the most efficient way to share a blessed reference among two or more objects?

For example, in main.pl I declare:

use Registry; use Queue; my $reg=Registry->new; my $queue=Queue->new;

Registry object stores configuration data for both main.pl and Queue.pm. I want $queue to access $reg, but not by means of use Registry inside package Queue, because I don't want to have more than one instance of Registry. How could I do it? Thanks in advance for any pointers, suggestions...

Replies are listed 'Best First'.
Re: Most efficient way to share blessed refence among packages
by sauoq (Abbot) on Oct 25, 2002 at 21:46 UTC

    It would be better to avoid making the Queue module dependent on the Registry module at all. You could allow the Queue constructor to take a Registry object as an argument but it's not a good idea.

    It would be better to extract the information that you need from the Registry and pass it to the Queue constructor as you need to. The following code is entirely hypothetical as I have no idea how your modules work but I would do it something like:

    use Registry; use Queue; my $registry = Registry->new(); my $queue = Queue->new( $registry->GetValue('MaxQueueSize') );
    -sauoq
    "My two cents aren't worth a dime.";
    
Re: Most efficient way to share blessed refence among packages
by gjb (Vicar) on Oct 25, 2002 at 21:46 UTC

    Why not simply define an static attribute registry in the class (or package if you wish) Queue? You could specify which registry to use by setting it via a class method setRegistry in class Queue.

    package Queue; my $register; sub new {...} sub setRegister { my ($pkg, $reg) = @_; $register = $reg; }
    and in main.pl:
    my $reg = Register->new(); my $queue = Queue->new(); Queue->setRegister($reg);

    This is the simplest approach just to give you the idea, and not how I'd actually do it, but I can elaborate if there's interest.

    Hope this helps, -gjb-

Re: Most efficient way to share blessed refence among packages
by robartes (Priest) on Oct 25, 2002 at 21:51 UTC
    How about making the reference to the Registry instance an attribute of the Queue instance that's passed along as a parameter to the constructor of Queue:
    use strict; package Queue; sub new { my ($self,$registry)=@_; return bless {'Registry'=>$registry}, ref($self)||$self; } # This code is untested, and might conceivably not work, # or work in strange and unpredictable ways not # excluding FedEx'ing a camel to your doorstep.
    The constructor can of course do with lots more error checking to make it robust, but this should give you an idea on how to proceed. The methods in Queue can than use the Registry attribute to access the registry object through the reference.

    CU
    Robartes-