質問

I am trying to do simple module usage in Perl:

Flame/Text.pm:

package Flame::Text;
sub words { … }
1;

Flame/Query.pm:

package Flame::Query;
use Flame::Text qw(words);
sub parse_query { words(shift); }
parse_query 'hi';
1;

Why am I getting the following error message?

Undefined subroutine &Flame::Query::words called at Flame/Query.pm line 3.

The following works just fine:

package Flame::Query;
use Flame::Text;
sub parse_query { Flame::Text::words(shift); }
parse_query 'hi';
1;
役に立ちましたか?

解決

You never imported or exported the words subroutine from the Flame::Text package. A statement use Some::Module @args is equivalent to:

BEGIN {
  require Some::Module;
  Some::Module->import(@args);
}

that is, the import method is called with the specified arguments. This method would usually export various symbols from one package into the calling package.

Don't write your own import, rather you can inherit one from the Exporter module. This module is configured by storing exportable symbols in the @EXPORT_OK global variable. So your code would become:

package Flame::Text;
use parent 'Exporter';  # inherit from Exporter
our @EXPORT_OK = qw/words/;  # list all subs which you want to export upon request

sub words { ... }

Now, use Flame::Text 'words' will work as expected.

他のヒント

You need to do something like this

package Flame::Text;
use Exporter 'import'; # gives you Exporter's import() method directly
@EXPORT_OK = qw(words);  # symbols to export on request

as perl doesn't export (or pollute) the namespace by default

http://perldoc.perl.org/Exporter.html

don't forget to

use strict; use warnings;

in all things perl

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top