
budman
User
Feb 11, 2012, 12:26 PM
Post #9 of 18
(2857 views)
|
|
Re: [naven8] using package in perl
[In reply to]
|
Can't Post
|
|
For testing purposes, or sometimes inclusion of related modules, you need to separate the scopes because everything defaults to the main package. Example:
{ package MyPack::Funcs; .... some code ... our $myvar = 'package var'; 1; # optional for inclusive packages, required for external } { package MyPack; import MyPack::Funcs; print $MyPack::Funcs::myvar; ... code ... 1; # optional for inclusive packages } package main; import MyPack; ... code ... Normally, you would use the 'use' command to load the modules - this is for external packages (*.pm). The 'use' command is actually a function that performs a 'require' on the module name, and then an 'import' to load the file into the namespace/package. The closure block { package ... } isolates each packages namespace, so they won't bleed into each other. Each package is now has a separate independent namespace. If you run across 'use vars', this will probably be deco'd in new releases, so use the 'our' command on variables you want to share between modules. You can try it without the imports, perl will try loading them implicitly as long as you don't call the modules with 'use'. Look into Exporter if you want to limit what gets imported into the main namespace. In your module 'MyPack' you can add:
use Exporter(); our @ISA = 'Exporter'; # explicit exports requires qw(sub1 sub2) in calling package our @EXPORT = "sub1 sub2 sub3"; # global exports our @EXPORT_OK = "sub4 sub5 $var"; Check out the perldoc perlmod for more tips.
(This post was edited by budman on Feb 11, 2012, 12:34 PM)
|