import a library subroutine while using FindBin in perl - 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);

Related

Can't find exported subroutine in Perl

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?
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 ();
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
Foo/Utilities.pm
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';
}
main.pl
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

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.

Perl module error regarding "undefined subroutine"

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);

Why can't my Perl script see the our() variables I defined in another file?

I have a question relating to Perl and scoping. I have a common file with lots of various variables. I require the common file in my main script, but I cannot access the variables; they seem to be outside of its scope. I assumed that an our declaration would overcome that problem, but it doesn't seem to work.
Script 1: common.pl
#!/usr/bin/perl
our $var1 = "something";
our $var2 = "somethingelse";
Script 2: ftp.pl
#!/usr/bin/perl
use strict;
use warnings;
require('common.pl');
print $var1;
I get the error: Global symbol "$var1" requires explicit package name
There's no require statement in your second example, but it wouldn't work anyway. What our does is declare a lexically-scoped package variable. Since you have no package statement, it uses the default package main. So your first script sets up the variable $main::var1, but this will only be available within that file's scope.
A better way to provide common variables for other scripts is to use Exporter. You can define package symbols in one place and Exporter will take care of copying them to the requesting script or class's namespace when needed.
I would put the config in a module instead.
File: MyConfig.pm
package MyConfig;
require Exporter;
use strict;
our #ISA = qw(Exporter);
our #EXPORT = qw( getconfig );
my %confighash = (
thisone => 'one',
thatone => 2,
somthingelse => 'froboz',
);
sub getconfig {
return %confighash;
}
1;
Example usage:
#!/usr/bin/perl
use strict;
use warnings;
use MyConfig;
my %config = getconfig();
print $config{ somthingelse };
This should print froboz
It looks like you need a proper configuration file there. I'd go for a non-code configuration file that you can read when you need to setup things. There are modules on CPAN to handle just about any configuration format you can imagine.
If you want to do it the way you have it, get rid of our and declare them with use vars. Don't let the PBP police scare you off that. :) You only really need our to limit a scope of a package variable, and that's exactly the opposite of what you are trying to do.
our() does something a little different than you think. Its sole purpose is to work with strict in requiring you to declare package variables that you are going to use (unless they are fully-qualified or imported). Like strict, its effect is lexically-scoped. To use it to allow accessing a global $main:var1 from multiple files (which are separate scopes) as just $var1, you need to say our $var1 in each file.
Alternatively, you would change your required file to be a module with its own package that exports the variables to any package that uses it.
Try this. I am new at Perl but this is how I got it to work on a script I made
#!/usr/bin/perl
$var1 = "something";
$var2 = "somethingelse";
Script 2: ftp.pl
#!/usr/bin/perl
use strict;
use warnings;
our $var1;
our $var2;
require('common.pl');
print $var1;