From everything I've read on using Perl modules, the basic usage is:
- Module file with
.pm
extension, which includes the statementpackage <name>
, where<name>
is the filename of the module without the extension. - Code file that uses module contains the statement
use <name>;
.
The application I'm coding has one main code script which uses about 5 modules. I had forgotten to include the package <name>
statement in the modules, but my code still ran just fine with the use <name>
statement. I started receiving Undefined subroutine
errors with one of the modules, so I added the package statement to each of the modules. Now the rest of those modules stopped working. What gives?
Example:
mainapp.pl
#!/usr/bin/perl
use UtyDate;
my $rowDate = CurrentDate("YYYYMMDD");
UtyDate.pm
#!/usr/bin/perl
package UtyDate;
sub CurrentDate
{
#logic
}
return 1;
When I run the above code, I get the error Undefined subroutine &main::CurrentDate called at...
. However, if I remove the package UtyDate;
line from UtyDate.pm, I get no error. This situation exists for several but not all of my modules.
There's obviously a lot more code I'm not showing, but I'm confused how any of the code I'm not showing could affect the package/use constructs I've shown here.
Besides using the exporter, as Gray points out, you could (UGLY, but works) also call the functions with the module name ..
You functiond/procedures don't work since they are now in a differen namespace (defined by the module name)
Alternatively to Gray's suggestion, you can do this:
When you use a module, the code in the module is run at compile time. Then import is called on the package name for the module. So,
use Foo;
is the same asBEGIN { require Foo; Foo->import; }
Your code worked without the
package
declarations because all the code was executed under the packagemain
, which is used by the main application code.When you added the
package
declarations it stopped working, because the subroutines you defined are no longer being defined inmain
, but inUtyDate
.You can either access the subroutines by using a fully qualified name
UtyDate::CurrentDate();
or by importing the subroutines into the current name space when youuse
the module.UtyDate.pm
Main program:
See Exporter docs for more info.
You are missing the exporter perl header code. You will need to add something like the following to the top of your pm file below the package statement:
See this link: http://perldoc.perl.org/Exporter.html#DESCRIPTION