Perl - Package/Module Issues

末鹿安然 提交于 2019-11-30 20:05:28

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 as BEGIN { require Foo; Foo->import; }

Your code worked without the package declarations because all the code was executed under the package main, 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 in main, but in UtyDate.

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 you use the module.

UtyDate.pm

package UtyDate;
use strict;
use warnings; 

use Exporter 'import';

# Export these symbols by default.  Should be empty!    
our @EXPORT = ();

# List of symbols to export.  Put whatever you want available here.
our @EXPORT_OK = qw( CurrentDate  AnotherSub ThisOneToo );

sub CurrentDate {
    return 'blah';
}

sub AnotherSub { return 'foo'; }

Main program:

#!/usr/bin/perl
use strict;
use warnings; 

use UtyDate 'CurrentDate';

# CurrentDate is imported and usable.    
print CurrentDate(), " CurrentDate worked\n";

# AnotherSub is not
eval {  AnotherSub() } or print "AnotherSub didn't work: $@\n";

# But you can still access it by its fully qualified name
print UtyDate::AnotherSub(), " UtyDate::AnotherSub works though\n";

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:

package UtyDate;
BEGIN {
  use Exporter ();
  use vars qw($VERSION @ISA @EXPORT);
  $VERSION = "1.0.0";
  @ISA = qw(Exporter);
  @EXPORT = qw( &CurrentDate );
}

See this link: http://perldoc.perl.org/Exporter.html#DESCRIPTION

Alternatively to Gray's suggestion, you can do this:

use UtyDate;
UtyDate::CurrentDate(...);

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)

use UtyDate;

UtyDate::CurrentDate(  )
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!