Reputation: 7433
I have a module called Utilities.pm
. It exports a subroutine called dummy_method
.
package Foo::Utilities;
use strict;
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(dummy_method);
sub dummy_method {
# do things
}
I have a Perl script that uses the dummy_method
subroutine:
use strict;
use warnings;
use Foo::Utilities qw('dummy_method');
my $foo = Foo::Utilities::dummy_method("foo");
print("$foo\n");
Executing that script throws an export error:
"dummy_method" is not exported by the Foo::Utilities module
Can't continue after import errors at /home/me/foo.pl line 3
BEGIN failed--compilation aborted at /home/me/foo.pl line 3.
I'm confused because I am explicitly exporting that subroutine with @EXPORT = qw(dummy_method);
. How do I use dummy_method
in another script?
Upvotes: 2
Views: 703
Reputation: 126722
The code you have written, with the modification suggested by ysth, works correctly. The only remaining possibility that I can think of is that you have named or located your module incorrectly
use Foo::Utilities 'dummy_method'
will load a file called Foo/Utilities.pm
where the Foo
directory is in one of the paths in your @INC
. It is a common error to omit the initial directories that must be in the path to the module, and you do say that your module is called just Utilities.pm
There must also be a Foo/Utilities.pm
that behaves differently, otherwise the use
statement would fail even to find the file
I have written your code in more modern Perl. This also works
package Foo::Utilities;
use strict;
use warnings 'all';
use Exporter 'import';
our @EXPORT = qw(dummy_method);
sub dummy_method {
print "dummy_method()\n";
'do things';
}
use strict;
use warnings;
use Foo::Utilities 'dummy_method';
my $foo = dummy_method('foo');
print("$foo\n");
There is no need for using vars
any more, and it has been better to import the import
method from Exporter
(instead of inheriting it) since Perl v5.8.7
Upvotes: 3
Reputation: 98388
Some people are obsessed with using qw for import lists, even if there is only one element. I think this makes others think this is a requirement, when it is just one way of making a list.
use Foo::Utilities qw('dummy_method');
says to import a method called 'dummy_method'
, not dummy_method
, just like print qw('dummy_method')
prints 'dummy_method'
, not dummy_method
.
Try instead:
use Foo::Utilities 'dummy_method';
or, if you must:
use Foo::Utilities qw(dummy_method);
Though since you are exporting it by default, you could just do:
use Foo::Utilities;
Or, since you are calling it as Foo::Utilities::dummy_method, not even export it by default:
use Foo::Utilities ();
Upvotes: 7