Generally it is a better idea to pass variable content to functions in other packages via function arguments, and to methods by e.g. binding them as attributes to an object of the foreign package. Sharing variables between packages can (or will) lead to confusion and should not be undertaken lightly.
That said - you can declare a package global inside package P and set it from within the package main (default namespace):
package P; use vars qw($f); sub foo { print "$f\n" } package main; $P::f = "howdy, world"; P::foo(); __END__ output: howdy, world
You can also share variables between packages assinging to typeglobs in the respective symbol table (see e.g. Of Symbol Tables and Globs):
package P; use strict; use vars qw($f); # NOTE: *f is a shared typeglob sub foo { print $f,"\n"; $f = "world"; } package main; use strict; use vars qw($f); # NOTE: *f shared with package P *P::f = *f; # make P::f an alias of main::f $f = "howdy"; P::foo(); # after this call, $f is changed! print $f,"\n"; __END__ ouput: howdy world
You should use this approach only if you know well what you are doing, and state prominently in whatever file that uses a shared typeglob that it is doing so, and why you need it. The $main::f variable can be changed also in P assigning to $f, and it will be changed in main as well, which would give you some surprise if you aren't aware of it.
--shmem
_($_=" "x(1<<5)."?\n".q·/)Oo. G°\ /
/\_¯/(q /
---------------------------- \__(m.====·.(_("always off the crowd"))."·
");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
In reply to Re: How can i pass a variable from a program to a module so that it is accessible to the entire module.???
by shmem
in thread How can i pass a variable from a program to a module so that it is accessible to the entire module.???
by sanjay nayak
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |