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

Oh, ye hallowed possessors of divine Perl wisdom...

I need to ask about modifying my variables defined in another module.

Assuming the following module:
package MODPERL::SausageGrinder; my $foo;
Within my code, I attempt the following:
use MODPERL::SausageGrinder; $MODPERL::SausageGrinder::foo = 1;

Yet when debugging, foo is later used within a subroutine defined within the SausageGrinder module. There, I'm seeing that foo is not set as I did within my code (calling module).

Is it possible to modify my variables within another module thy lowly newbie humbly asks?

Replies are listed 'Best First'.
Re: modifying module variables?
by ikegami (Patriarch) on May 29, 2009 at 19:27 UTC
    No. my $foo; is a different variable than another my $foo;, and it's a different variable than package variable $any::package::foo. You could use our instead of my to access the package variable without using its full name.
    package MODPERL::SausageGrinder; $MODPERL::SausageGrinder::foo = "bar"; our $foo; # Associates $foo with $MODPERL::SausageGrinder::foo print $foo; # bar
Re: modifying module variables?
by DStaal (Chaplain) on May 29, 2009 at 19:30 UTC

    Given this is Perl, I expect there is some way to do it...

    But why? The whole point of these modules is to maintain that separation you are trying to break: It makes for easier to maintain, and less buggy, code. Trying to get around it should usually be the absolute last resort. (After even copy-pasting the module's code into a new module and writing an interface to do whatever it is you are trying.)

    Please, explain what you are trying to do. I'll bet we can find a better way than modifying another package's private variables.

Re: modifying module variables?
by Perlbotics (Archbishop) on May 29, 2009 at 19:42 UTC

    Maybe this comes close to what you want without changing too much?

    use strict; package MODPERL::SausageGrinder; my $foo = 0; sub printfoo { print "foo is $foo\n"; } sub setfoo { $foo = shift; } package MAIN; MODPERL::SausageGrinder::printfoo; MODPERL::SausageGrinder::setfoo(42); MODPERL::SausageGrinder::printfoo; # prints: # foo is 0 # foo is 42
    However, as DStaal already suggested, there is probably a better way... described in the tutorials OO-Section...