Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't my Perl script use my module?

module.pm

package module;
use 5.012;
use warnings;

sub Parse
{
   return 1;
}

1;

script.pl

#!/usr/bin/perl -w

use 5.012;
use warnings;
use lib 'C:/';
use module;

print Parse("value");

Stdout

Undefined subroutine &main::Parse
like image 655
Eric Fossum Avatar asked Feb 21 '23 03:02

Eric Fossum


2 Answers

You need either to write:

print module::Parse("value");

or to change the module package to export the name Parse.

See http://perldoc.perl.org/perlmod.html#Perl-Modules for guidance in exporting symbols from your module.

(By the way, you should really name your module Module rather than module. Lowercase module-names are used for Perl built-in features like use warnings and use strict.)

like image 103
ruakh Avatar answered Feb 27 '23 15:02

ruakh


Several things:

  • First, use Local as your module prefix. That way, if you just happen to have a module with the same name in your Perl installation, it will use yours. Call it "Local::Module". Then, create a Local directory, and name your module Module.pm.

  • The other thing you have to understand is that you define your module in another namespace. By default, everything is in the main namespace until you use the package statement. That creates another namespace that your package uses. This way, if your package has a function foo, and you've defined a function foo in your main program, they won't collide.

Thus, you have two choices: One (the preferred now) is to simply call your subroutine with the full package name prepended to it. The second is to export your subroutine names to your main program. This can cause problems with duplicate names, but you don't have to keep typing in the package name every time you call your subroutine.

Without Exporting the name

Local/Module.pm

# /usr/bin/env perl
# Local/Module.pm
package Local::Module;

use strict;
use warnings;

sub Parse {
    my $value = shift;  #Might as well get it.

    print "I got a value of $value\n";
    return $value;
}
1;    #Need this or the module won't load

program.pl

# /usr/bin/env perl
# program.pl

use strict;
use warnings;

use Local::Module;

Local::Module::Parse("Foo");

With export:

Local/Module.pm

# /usr/bin/env perl
# Local/Module.pm
package Local::Module;

use strict;
use warnings;
use Exporter qw(import);
our @EXPORT_OK(Parse);   #Allows you to export this name into your main program

sub Parse {
    my $value = shift;  #Might as well get it.

    print "I got a value of $value\n";
    return $value;
}
1;    #Need this or the module won't load

program.pl

# /usr/bin/env perl
# program.pl

use strict;
use warnings;

use Local::Module qw(Parse);

Parse("Foo");
like image 44
David W. Avatar answered Feb 27 '23 16:02

David W.