access to the variable in other pm
bogum
created: 2006-02-02 16:45:56
Hello All, I have following question regarding accessing variable from other module: In test.pm I have following:
#BEGIN OF THE TEST.PM 
package test; 

use strict; 
use warnings; 

# 
# The object responsible for managing the database connections. 
# 
my $dbaccess = undef; 

#somewhere else 
$dbaccess = new tmp::tmp2::DBAccess( %dbURL); 


#END OF THE TEST.PM 
In test2.pm I have following:
#BEGIN OF THE TEST2.PM 
package test2; 

use strict; 
use warnings; 

# How to access dbaccess from test.pm?? 

#END OF THE TEST2.PM 
My question is how to access $dbaccess variable (object) defined and initialized in test.pm within test2.pm module? I can not change anything in test.pm. Thanks, Bogumil
Re: access to the variable in other pm
created: 2006-02-02 17:06:47

make sure your module 1 exports the symbol you want

if say..
main.cgi is doing

use TEST1;
use TEST2;

and TEST1.pm is exporting $dbaccess as...

package TEST1;

use vars qw{$VERSION @ISA @EXPORT @EXPORT_OK};
require Exporter; @ISA = qw(Exporter); 
@EXPORT = qw($dbaccess);  # just to calling package !
$VERSION = '0.01';
use strict; 

my $dbaccess= 'whatever';

then TEST2.pm would...

$main::dbaccess->prepare('yo 5h1+3');

#or .. 

$TEST1::dbaccess->prepare('yo 5h1+3');


# play around. 
Re^2: access to the variable in other pm
created: 2006-02-03 06:50:19
make sure your module 1 exports the symbol you want

Well, not necessarily: he may write accessory subs to be used like methods and call them... ehm, like methods. This may be either an overkill or The Best Way™ depending on the actual purpose, scope and aim of his code. But indeed your suggestion is more akin to what the OP actually asked. As a side note, I'd just add

use base 'Exporter';
our @EXPORT = qw($dbaccess);  # hey, I always C at the very top!

as another, fundametally identical - but somewhat more modern, "WTDI".

Re: access to the variable in other pm
created: 2006-02-02 17:40:24
I can not change anything in test.pm.

Then you're in trouble, unless you install CPAN://PadWalker and somehow get ahold of the topmost pad for the test package, shuffle through it to find the appropriate slot for $dbaccess, and keep ahold of the reference.

It's not impossible by any means -- but the easiest way by far is to change test.pm.

perlmonks.org content © perlmonks.org and blazar, bogum, chromatic, leocharre

prlmnks.org © 2006 edmund von der burg (eccles & toad)

v 0.03