in reply to Re: accessing subs/methods from the module
in thread accessing subs/methods from the module

Right sorry if my thing is a bit convoluted. Let me try again. I have two objects using 2 different classes. One is say called $f thats an instance of class "Foobar." The other is $b of class "Blah." They're both modules.

My question would be, can I inside the module for "Blah" access a variable in the main program? That variable also happens to be $f, an instance of "Foobar."

Let me fix my example too.

main code:

use Blah; use Foobar; $b = Blah->new(); $f = Foobar->new(); $b->doSomething;

and inside the Blah module:

sub new { ... } sub doSomething { $f->methodX(); }

And inside the Foobar module:

sub new { ... } sub methodX { does some fun things here }

So basically, method "doSomething" is invoked. I want to be able for "doSomething" to access variable in the main program $f. $f just happens to be an instance of "Foobar."

Thanks!

Replies are listed 'Best First'.
Re: Re: Re: accessing subs/methods from the module
by artist (Parson) on Feb 06, 2003 at 20:23 UTC
    I think it's very simple:

    if you change in the main program,

    $b->doSomething;
    to
    $b->doSomething($f);
    and
    package Blah; sub doSomething { my $self = shift; my $f = shift; $f->methodX; } ...
    That should work for you.

    artist

Re: Re: Re: accessing subs/methods from the module
by steves (Curate) on Feb 06, 2003 at 19:20 UTC

    It's bad style, but yes:

    package Blah; sub doSomething { $main::f->whatever(); }
    As long as $f is a package variable in main -- i.e., not declared with my, my preference being:
    our $f = Foobar->new();
    ... and as long as I don't have to maintain your code. You have factoring issues here that should be keeping you awake at night.

      Great thanks!

      Not really up to me, I thought it wasn't the best in design either. However, it does beat some other alternatives we thought up.

Re3: accessing subs/methods from the module
by dragonchild (Archbishop) on Feb 06, 2003 at 20:14 UTC
    $b->doSomething($f); package Blah; sub doSomething { my $self = shift; my ($f) = @_; $f->methodX(); }
    The real question is how do I use a variable in one scope within another scope. The answer is you pass it. This isn't an OO question, it's a scoping question. It's also a pretty basic question.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.