Another problem I have encountered whilst creating my set of modules. Say I have my set of modules that are named as follows:

Module::Main
Module::Section1
Module::Section2

Now, let's say that I have the following code in index.pl:

#!/usr/bin/perl -w use strict; use Module::Main; my $REQ = new Module::Main; $REQ->init(); $REQ->start_it();
This is the start of it. Now, a couple of other modules are added to the mix...

Module::Main contains something like the following:

package Module::Main; sub new { my $class = shift; my $self = {}; bless ($self, $class); return $self; } sub init { my $self = shift; $self->{SEC1} = new Module::Section1; $self->{SEC2} = new Module::Section2; return 1; } sub start_it { my $self = shift; $self->{SEC1}->do_something(); return 1; }
And now, let's say that Module::Section1 contains something like this:

package Module::Section1; sub new { my $class = shift; my $self = {}; bless ($self, $class); return $self; } sub do_something { my $self = shift; =cut HERE! Now I need to access $REQ->{SEC2}->method(); The problem? $self now contains the object specific to Module::Section1 (ie: $REQ->{SEC1}, not to $REQ. So I can't do $self->{SEC2}->method(). I could always change the my() declaration in index.pl to an our() and then use $::REQ->{SEC2}->method(), but this just defeats the purpose of using OO programming! Besides, this would require that the variable be named $REQ and not anything else. I could always pass a reference to $REQ to everything subroutine/method, but that just seems extremely messy and bad programming style. So how can I accomplish this? =cut }

In reply to Accessing Methods of Another Package by mt2k

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.