Perl module error regarding "undefined subroutine" - perl

I am trying to use a module called Math::Counting:
#!/usr/bin/perl
use strict;
use warnings;
use Math::Counting;
my $f = factorial(3);
print "$f\n";
When I run it however, I get the following error
$ perl UsingModules.pl
Undefined subroutine &main::factorial called at UsingModules.pl line 8.
It seems like the function factorial is not being exported, but why?
When I used the following
my $f = Math::Counting::factorial(3);
instead of what was above, it works perfectly fine, but I am curious why the function cannot be exported.
I am using perl v5.10.1 on Cygwin.

There is a bug in the module. Math::Counting ISA Exporter, but Math::Counting does not load Exporter.
Workaround: You can require or use Exporter manually.
Better: File a bug with the module author, provide a test case.
Comment:
Oh, very interesting. The module author does test his functions, but Test::More pulls in Exporter, meaning that this omission from the module source was not noticed.
Update:
Math::Counting 0.0904 has been released, addressing this issue.

Math::Counting looks a little silly (I mean student versus engineering modes?) The real factorial function provided by the module, bfact is a thin wrapper around Math::BigInt::bfac. So, just use Math::BigInt.
#!/usr/bin/env perl
use strict; use warnings;
use Math::BigInt();
print Math::BigInt->bfac('300'), "\n";
Output:
30605751221644063603537046129726862938858880417357699941677674125947653317671686
74655152914224775733499391478887017263688642639077590031542268429279069745598412
25476930271954604008012215776252176854255965356903506788725264321896264299365204
57644883038890975394348962543605322598077652127082243763944912012867867536830571
22936819436499564604981664502277165001851765464693401122260347297240663332585835
06870150169794168850353752137554910289126407157154830282284937952636580145235233
15693648223343679925459409527682060806223281238738388081704960000000000000000000
0000000000000000000000000000000000000000000000000000000
No, I did not verify the result.
As others have noted, Math::Counting has:
our #ISA = qw(Exporter);
our #EXPORT = qw(
factorial permutation combination
bfact bperm bcomb
);
but there is no require Exporter.
In fact, there is no need for this module to inherit from Exporter. A simple:
use Exporter 'import';
would have been enough. Also, there really is no need to pollute the namespace of a user of this module by default, so it should have:
our #EXPORT = ();
our #EXPORT_OK = qw(
factorial permutation combination
bfact bperm bcomb
);
Otherwise, what's the point of defining %EXPORT_TAGS?

It seems that Math::Counting is missing require Exporter; so none of it's functions are being exported to your namespace.

After being alerted by a nice person who filed a bug report with CPAN regarding my forgotten require statement, I fixed up the module export, including the comment about "polluting the namespace."
Also, I added a note that it is a "thin wrapper" for Math::BigInt->bfac() for real world applications, in the docs. When I made it, I could not find simple computations for permutation or combination. Now there are a plethora...

It seems the Math::Counting module did not export the factorial method when you called it using use Math::Counting.
The CPAN page does the following
use Math::Counting ':student';
and afterwards the factorial method is exported into your namespace, and you can use it without prepending the entire package name.

Take a look at the source code for Math::Counting and see what version it is. You can find where the source is located by doing this:
prompt> perldoc -l Math::Counting
You can also find the version of a module about 90% of the time by looking at the module's $VERSION variable:
use Math::Dumper;
print "The version of Math::Dumper is $Math::Dumper::VERSION\n";
I just downloaded version 0.0902, and the following program works just fine:
#! /usr/bin/env perl
#
use strict;
use warnings;
use feature qw(say);
use Math::Counting;
say $Math::Counting::VERSION;
say factorial(6);
I notice in this version, he has:
our #ISA = qw(Exporter);
our #EXPORT = qw(
factorial permutation combination
bfact bperm bcomb
);
So, it looks like the author is automatically exporting all of their subroutines in this particular version. The author also has two groups of export tags defined :student, and big.
It could be in earlier versions, he didn't have #EXPORT defined, but used #EXPORT_OK (which is preferable), and you had to do this:
use Match::Counting qw(:student);
or
use Math::Counting qw(factorial);

Related

Include another script in my parent Perl script

How can I include another Perl script in my base Perl script?
I have a primary source file test.pl and I want to include secondary sóurce file config.pl within it.
What is a standard method to achieve this in Perl?
(I'm guessing that the program called config.pl sets config values that you want to access in test.pl. You don't make that clear in your question.)
A simple example. If config.pl looks like this:
#!/usr/bin/perl
$some_var = 'Some value';
Then you can write test.pl to look like this:
#!/usr/bin/perl
use feature 'say';
do './config.pl';
say $some_var;
But this is a terrible idea for many reasons. Not least because it stops working when you add use strict and use warnings to either of the files (and you should aim to have use strict and use warnings in all of your Perl code).
So what's a better approach? Turn your configuration into a proper module that returns a hash (I only have a single scalar variable in my example above, but a hash gives you a way to deliver many values in a single variable). A simple approach might look like this.
A module called MyConfig.pm:
package MyConfig;
use strict;
use warnings;
use parent 'Exporter';
our #EXPORT = qw[config];
sub config {
my %config = (
some_var => 'Some value',
);
return %config;
}
1;
And a test.pl like this:
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use FindBin '$Bin';
use lib $Bin;
use MyConfig;
my %config = config();
say $config{some_var};
Having got that working, you can add improvements like parsing the %config hash from an external file (perhaps stored in JSON) and then allowing different configurations for different environments (development vs production, for example).
It's a little bit more work than your current approach, but it's far more flexible. And you can use strict and warnings.

perl declare and export variables from a module

I need to modify a bunch of scripts to do the equivalent of a straight C style "include" of a moderate number of variables. After the "use" to pull these in it should act exactly as if a line like this had been included:
my $os_name = "Windows"; #declares the variable AND sets its value
So that they may be used in the "calling" script. There is a little bit of logic in the module that conditionally sets the values of these variables. The scripts all have "use strict". A typical "caller" has:
use strict;
use File::Basename;
use lib dirname (__FILE__);
use os_specific;
print "DEBUG os_name $os_name\n";
and the module (os_specific.pm) has:
package os_specific;
use warnings;
use strict;
use Exporter;
our #EXPORT = qw($os_name);
our $os_name="Windows";
1
But it doesn't work, there are compile stage warnings like:
Global symbol "$os_name" requires explicit package name at caller.pl.
So the declaration of the variable in the module is not effective at the caller's scope.
Can this be done, or must each of these variables also be declared in caller.pl? (All responses please employ "use strict" - without that it can be done using a "require". That doesn't work with "use strict" though because it throws a compile time error.)
I know the variables from the module can be used as "$os_specific::os_name", the question is how to set this up so that they can be used as just "$os_name".
Thanks.
The problem is that you aren't inheriting any functionality from Exporter because you haven't set the #ISA package variable.
Your module should look like this, after fixing the package name (packages should use upper and lower case letters only, by convention) and should be in the file OSSpecific.pm
package OSSpecific;
use strict;
use warnings;
use Exporter;
our #ISA = qw/ Exporter /;
our #EXPORT = qw/ $os_name /;
our $os_name = "Windows";
1;
You need an explicit import method in your package, as demonstrated in Exporter.
You also need to fix the casing of your package name, the filename, and your use statement so they all match.
OS_Specific.pm:
package OS_Specific;
use warnings;
use strict;
use Exporter qw(import);
And the other file:
use OS_Specific;
Check out perlstyle for useful guidelines on picking package names:
Perl informally reserves lowercase module names for "pragma" modules like integer and strict. Other modules should begin with a capital letter and use mixed case, but probably without underscores due to limitations in primitive file systems' representations of module names as files that must fit into a few sparse bytes.

Equivalent to: import *

I am creating a Perl equivalent to my Python project.
Description:
I have a base module "base.py" that is used by all my scripts via "from base import *"
The base module has common subroutines/functions that can be executed inside the scripts
My attempt for Perl was placing inside each script "use base.pm". However the subroutines in Perl were not locally imported to the script so I needed to make a call to the "base" module each time I wanted to execute a subroutine. What is the Perl equivalent to Python's "from base import *"?
A few things:
The Local namespace is good to use for your local modules. Perl specifically reserves Local for this purpose. No official module will ever be in the Local namespace.
Perl is not Python. Perl will do things a bit differently. Sometimes there's an exact equivalent, sometimes not. This does not have an exact equivalent. Close, but not exact.
Method #1: Don't Export Any Functions
All functions you defined in your modules are available if you prefix the full namespace to it. This is the easiest way to define and use functions from your modules and is the least likely to cause problems. It's easy to see where a function came from, and you won't have a problem with two modules using the same function name.
I have a module called Local::Base that has a single function in it. My program can use this function, by simply referring it as Local::Base::foo:
My Program
use strict;
use warnings;
use feature qw(say);
use Local::Base;
my $foo_string = Local::Base::foo("string");
say "Foo: $foo_string";
Local/Base.pm
package Local::Base;
use strict;
use warnings;
sub foo {
my $string = shift;
return qq(I've foo'd "$string"!);
}
1;
Method #2: Use the Exporter Pragma to Specify What to Automatically Export
Perl has a special pragma called Exporter that allows me to specify which modules will automatically be imported into my program.
This is not like Python where I can specify any defined function. Instead, I have to list the ones I want to export. This has a disadvantage over Python's way: In Python, if I write a new function, it's automatically imported without me having to do anything. It also has a big advantage over Python's way: In Python, if I write a new function, it's automatically imported without me having to do anything whether I wanted it imported or not. You can imagine if I wrote a private function I didn't want people to use. In Python, it would automatically be available. In Perl, it wouldn't be unless I specified it:
My Program
use strict;
use warnings;
use feature qw(say);
use Local::Base;
my $foo_string = foo("string");
say "Foo: $foo_string";
Local/Base.pm
package Local::Base;
use strict;
use warnings;
use Exporter 'import';
our #EXPORT = qw(foo);
sub foo {
my $string = shift;
return qq(I've foo'd "$string"!);
}
1;
Now, whenever I use Local::Base, the foo function is automatically imported.
Notice that I list all functions I want to export in the #EXPORT array. (Also note I declare that array with an our instead of a my. That our means the #EXPORT is a PACKAGE variable.). Also notice the qw(...) syntax. This is quote word. All words are separate elements of an array. You don't use commas:
my #array = ("one", "two", "three");
my #array = qw(one two three);
Both of these are equivalent. You also may see it this way:
my #array = qw/one two three/;
I like the parentheses, but the forward slashes tend to be the standard.
Method #3: Be Nice When Exporting
It is not recommended you use automatic exporting any more. Older modules like File::Copy still do it, but newer modules make you import your stuff. This also uses the Exporter pragma, but I specify #EXPORT_OK instead of just #EXPORT.
Now, when I specify I want to use Local::Base, I have to specify the functions I want to import into my program:
My Program
use strict;
use warnings;
use feature qw(say);
use Local::Base qw(foo);
my $foo_string = foo("string");
say "Foo: $foo_string";
Local/Base.pm
package Local::Base;
use strict;
use warnings;
use Exporter 'import';
our #EXPORT_OK; = qw(foo);
sub foo {
my $string = shift;
return qq(I've foo'd "$string"!);
}
1;
This forces the user to document the functions in your module they want to use. This way, they know where imported functions came from. It enforces good programming practice. Plus, if you use multiple modules and they have similar function names, you can make sure you use the one from the module you want. (Remember, you can still specify the package name prefixed before the function if you want to use the other one).
What if I am a Python programmer and I don't care about good programming practices? (Wait, that didn't come out quite right...) You can still (sort of) do it the Python way by specifying a Regular Expression (after all this is Perl):
use Local::Base '/.+/';
This will export all modules listed in both #EXPORT and #EXPORT_OK that match this regular expression. Since this matches everything, it will import everything you listed in #EXPORT and #EXPORT_OK. It won't import all functions. It will only import the functions in the #EXPORT and #EXPORT_OK arrays. Of course, you can specify any regular expressions and even ant-regular expressions. This will export all exportable functions except those with bar in the name:
use Local::Base '!/bar/';
Take a look at the Exporter pragma, and see what other goodies it has. For example, you can group functions into tags. That way, users can specify a particular set of functions with just a tag. See Math::Trig for a good example.
Hope this helps.
Sorry for the long answer, but I'm married with kids. Like, I'm doing anything else on New Years Eve.
You generally specify which functions to import just as a list of names:
use List::Util 'max', 'min';
Most modules that export things will follow these semantics:
use MyBase; # imports default exports (if any)
use MyBase 'baz'; # imports only baz
use MyBase (); # import nothing
Inside the module, an import class method is called that can choose what to export, usually having a default list but using the list passed if there is one. The Exporter module exists to help you do this:
package MyBase;
use Exporter 'import';
our #EXPORT = ( 'foo', 'bar' );
our #EXPORT_OK = ( 'baz', 'quux' );
There is also a facility for grouping exports by tag and allowing importing a whole group easily, see the Exporter docs. Variables can also be exported, not just subs.
With that background, to finally answer your question:
For modules that use Exporter (not all do), you can specify imports with a regular expression enclosed in //:
use List::Util '/./';
First of all base.pm is a very bad name as it is a core module. Second, exportable functions must be declared as such (usually), see Exporter for examples.

import a library subroutine while using FindBin in perl

EDIT
Sorry for the confusion, here is my updated question.
I am using FindBin in my perl script like this:
use FindBin qw($Bin);
use lib "$Bin/../lib";
use multi_lib qw(say_hello_world);
This works:
multi_lib::say_hello_world();
but this does not:
say_hello_world();
EDIT 2
This is how multi_lib.pm looks:
package multi_lib;
use strict;
use warnings;
use 5.010;
require Exporter;
my #ISA = qw(Exporter); # removing `my` causes an error!
my #EXPORT_OK = qw(say_hello_world); # removing `my` causes an error!
sub say_hello_world {
say "hello world!";
}
p.s.
I have no idea what does #ISA stand for and if adding the my is OK... I followed the preldoc for Exporter.
Edit 3
I think I solved it by moving #EXPORT_OK before use strict. I am used to put use strict right at the beginning of my scripts but I guess this is not the way to go here (?). Anyway, this works:
use Exporter 'import';
#EXPORT_OK = qw(say_hello_world);
use strict;
...
I would still appreciate some explanations as to what exactly is going on here and what is the recommended way of exporting subroutines (like I did?).
You can't do that. lib's import() routine modifies #INC instead of trying to export anything.
But in any case, there are no functions in lib.pm that are suitable for external use. What are you really trying to accomplish?
Updated answer for updated question:
No, you cannot use my() on #EXPORT_OK; it needs to be globally visible so Exporter can use it.
Say our #EXPORT_OK; instead. The same is true for #ISA; the package variable #ISA controls inheritance, a lexical #ISA does nothing. I prefer not inheriting from Exporter, though; you do this (except with very old Exporter) by just importing Exporter's import routine:
use Exporter 5.57 'import';
The error you got that prompted you to add my() was because you specified use strict; (which, among other things, requires that variables be properly declared unless they are package variables qualified by package name or special global variables). our() is the equivalent to my() that declares variables as package variables instead of lexicals, so they are accessible from outside the scope in which they are declared. It's better to properly declare them with our() than to just move them above use strict; to get around the error.
That's not the way libraries work. You need to set your library location then load a module (.pm) from it that contains the subroutine you want.
I would like to imprt a specific
subroutine (aka say_hello_world) from
lib, but this does not work:
use lib "$Bin/../lib" qw(say_hello_world);
The use lib just points you to the directory where the files are, you need to specify the file as well. If your subroutine is in a file Example.pm then you need
use Example qw(say_hello_world);
Also note that the FindBin part needs to be inside a BEGIN block:
BEGIN {
use FindBin qw($Bin);
use lib "$Bin/../lib";
};
use Example qw(say_hello_world);

Is there a way to "use" a single file that in turn uses multiple others in Perl?

I'd like to create several modules that will be used in nearly all scripts and modules in my project. These could be used in each of my scripts like so:
#!/usr/bin/perl
use Foo::Bar;
use Foo::Baz;
use Foo::Qux;
use Foo::Quux;
# Potentially many more.
Is it possible to move all these use statements to a new module Foo::Corge and then only have to use Foo::Corge in each of my scripts and modules?
Yes, it is possible, but no, you shouldn't do it.
I just spent two weeks to get rid of a module that did nothing but use other modules. I guess this module started out simple and innocent. But over the years it grew into a huge beast with lots and lots of use-statements, most of which weren't needed for any given run of our webapp. Finally, it took some 20 seconds just to 'use' that module. And it supported lazy copy-and-paste module creation.
So again: you may regret that step in a couple of months or years. And what do you get on the plus side? You saved typing a couple of lines in a couple of modules. Big deal.
Something like this should work:
http://mail.pm.org/pipermail/chicago-talk/2008-March/004829.html
Basically, create your package with lots of modules:
package Lots::Of::Modules;
use strict; # strictly optional, really
# These are the modules we want everywhere we say "use Lots::Of::Modules".
# Any exports are re-imported to the module that says "use Lots::Of::Modules"
use Carp qw/confess cluck/;
use Path::Class qw/file dir/;
...
sub import {
my $caller = caller;
my $class = shift;
no strict;
*{ $caller. '::'. $_ } = \*{ $class. '::'. $_ }
for grep { !/(?:BEGIN|import)/ } keys %{ $class. '::' };
}
Then use Lots::Of::Modules elsewhere;
use Lots::Of::Modules;
confess 'OH NOES';
Yes.
In Foo/Corge.pm
use Foo::Bar;
use Foo::Baz;
use Foo::Qux;
use Foo::Quux;
1; # Be successful
All that is left is to get the directory containing sub-directory Foo added to your library path (#INC). Alternatively, create Foo.pm and have it use the other modules. They would be in a Foo sub -directory beside Foo.pm.
If you think about it, all the complex Perl modules that use other modules do this all the time. They are not necessarily in the same top-level package (Foo in this example), but they are used just as necessarily.
While you could use Carp, and Path::Class and confess, and so on (as jrockway suggests), that seems like overkill from where I'm sitting.
[EDIT: My earlier solution involving use Lots::Of::Modules; had a subtle bug -- see bottom. The fix makes things a bit uglier, but still workable.]
[EDIT #2: Added BEGIN { ... } around the code to ensure that any functions defined are available at compile time. Thanks to jrockway for pointing this out.]
The following code will do exactly what jrockway's code does, only simpler and clearer:
In Lots/Of/Modules.inc:
use Carp qw/confess cluck/;
use Path::Class qw/file dir/;
0; # Flag an error if called with "use" or "require" instead of "do"
To import those 4 functions:
BEGIN { defined( do 'Lots/Of/Modules.inc' ) or die; }
Because we don't have a package Lots::Of::Modules; statement at the start of this file, the use statements will export into the caller's package.
We must use do instead of use or require, since the latter will only load the file once (causing failure if use Lots::Of::Modules; is called more than once, e.g. in separate modules used by the main program). The more primitive do does not throw an exception if it fails to find the file named by its argument in #INC, hence the need for checking the result with defined.
Another option would be for Foo::Corge to just re-export any items of interest normally:
package Foo::Corge;
use base 'Exporter';
BEGIN {
our #EXPORT_OK = qw( bar baz qux quux );
use Foo::Bar qw( bar );
use Foo::Baz qw( baz );
use Foo::Qux qw( qux );
use Foo::Quux qw( quux );
}
1;
(The 'use' statements can probably go outside the BEGIN, but that's where they were in the code I checked to verify that this worked the way I thought it did. That code actually evals the uses, so it has a reason for them to be inside BEGIN which likely doesn't apply in your case.)
using #EXPORT instead #EXPORT_OK , is more simple
Library is :
package mycommon;
use strict;
use warnings;
use base 'Exporter';
our #EXPORT = qw(test);
sub test {
print "this is a test";
}
1;
use it:
#!/usr/bin/perl
use strict;
use warnings;
use mycommon;
common::test()