http://www.perlmonks.org?node_id=985533

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

Hi,

I could really do with a hand on some OO perl that I'm battling with please perlmonks.

Here is what I'm trying to do: I have 2 packages

LogSimple DEC::Project

The LogSimple logging object is created like so, the important piece to focus on here in this object is the function reference stored in 'exit'

my $log = LogSimple->new( logdir => $logdir, logfile => $logfile, loglevel => $loglevel, verbosity => $verbosity, exit => \&DEC::Project::exit_routine );

Next I initialise the following object, there can be multiples of these with different serial numbers.

my $server = DEC::Project->new( serial => '17353', log => $log, );

The LogSimple object handles any exit from the project like this:

$log->err("Something went wrong",1);

Where the script would exit 1. I use the LogSimple package in other projects and have recently added the optional ability to make a callback so that 'stuff' can take place before the exit..

Now, when something goes wrong talking to $server object I would like to call the subroutine

\&DEC::Project::exit_routine

I can get exit_routine to execute except I want to be able to issue commands to all of the $server objects from \&DEC::Project::exit_routine just before the exit.

I am trying to store references to all of the $server objects as they are created in ->new inside a global hash like this:

$server_objects{$options{'serial'}} = \$self;

My thinking is that I should be able to loop through the hash executing whatever methods I need against all of the objects like this:

sub exit_routine { for my $serial ( keys %server_objects ) { my $server = $server_objects{$serial}; my @ret = $server->logout(); } } sub logout { my $self = shift; print "logging out"; } };

However I keep running into the following: Can't call method "logout" on unblessed reference

This is my first real venture into OO programming so this is a real challenge for me. Anyone able to offer advice ?

Many thanks, Darren

Replies are listed 'Best First'.
Re: Storing object references during creation of ->new object
by tobyink (Canon) on Aug 05, 2012 at 15:21 UTC

    Not this:

    $server_objects{$options{'serial'}} = \$self;

    This instead:

    $server_objects{$options{'serial'}} = $self;
    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
      Thank you for the quick response. When I drop the \ I get:
      Can't call method "logout" on unblessed reference
        Here is the entire sub new:
        sub new { my $class = shift; my %options = @_; my $self = { _serial => $options{'serial'}, _log => $options{'log'}, _horcm => $options{'horcm'}, _does_get_cmd_status => $options{'does_get_cmd_status'}, }; bless $self, $class; $array_objects{$options{'serial'}} = $self; return $self; }