Subroutine undefined

I am trying to use a simple module 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 routine &Flame::Query::words , called in the line Flame / Query.pm.

The following works fine:

 package Flame::Query; use Flame::Text; sub parse_query { Flame::Text::words(shift); } parse_query 'hi'; 1; 
+6
source share
2 answers

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

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

that is, the import method is called with the specified arguments. This method usually exports different characters from one package to the calling package.

Do not write your own import , rather you can inherit it from the Exporter module. This module is configured by storing exported characters in the global variable @EXPORT_OK . Thus, your code will be as follows:

 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.

+10
source

You need to do something like this

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

since perl does not export (or pollute) the default namespace

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

Do not forget

 use strict; use warnings; 

in all things perl

+7
source

All Articles