Perl use Package - AH01215: Undefined subroutine - perl

I'm using the package URI::Escape. Usually, I can call the functions directly by naming it, e.g. uri_unescape('some text') but actual I'm getting AH01215: Undefined subroutine &MyFunctions::uri_unescape called at ...
This happens in an own package ('MyFunctions') of me. I got the use URI::Escape line. When I use &URI::Escape::uri_unescape it seems to work fine. But I just don't get why it is looking for this subroutine in my package...
Can someone explain it to me? Is there any way to solve this? I really don't wanna write this whole package-name::funktion every time I call this function :/

The subroutines are imported into the current namespace. You have to put the use line after the package declaration:
package MyFunctions;
use URI::Escape;
Otherwise, the functions are imported into the previous namespace, which is probably main in your case (you can verify by running main::uri_unescape().

Related

How to use one module in another module in perl?

Iam writing a perl script ,in which iam using a module utils.pm and in utils.pm iam using another module DB.pm in which i have a sub routine connetToDB().
in utils.pm iam writing
use DB qw (connectToDB());
and below iam calling that subroutine as
my $connection=DB::connectToDB(); (This is line 30)
it is giving an error like follows. Can someone pls help?
Undefined subroutine &DB::connectToDB called at utils.pm line 30.
you can see the DB.pm code here
The direct error in the shown code is that inside qw() you need names. The use pragma
Imports some semantics into the current package from the named module
(my emphasis). The "connectToDB()", with parentheses, is not the correct name for the subroutine. The error message simply says that it didn't find such a sub.
So just drop the parens, use DB qw(connectToDB);.
The code for the package was added to the question and here are some comments.
A similar fix is needed with your #EXPORT: you need the subroutine names (lose &).
Perhaps more importantly, you defined the sub using prototypes. Your sub is consistent with the prototype you use so I'll assume that it's done on purpose.
This is a very advanced (mis?)feature, which is very different from similar looking devices in other languages and is normally not needed. Chances are that you expect wrong things from prototypes. Go search for it. I'd advise against.
A side note: the prototype-related () and & are not a part of the subroutine name.
The last executed statement that returns in a module must return true, or code won't compile. The convention to ensure this is to put 1; at the end of the package.
Finally, you shouldn't name the module DB as that namespace is used internally by Perl. Also, such a generic name is just not good for a module -- it makes it easy to run into conflicts.
use DB qw(connectToDB);
my $connection=DB->connectToDB();
or
if you have defined a constructor "new" in DB.pm module then
my $connection=DB->new();
my $result = $connection->connectToDB();

Explain this witchcraft!!! (in Perl, with Moose and namespace::autoclean)

So these days I'm working with a project that uses Perl and Moose. I understand Moose is built on MOP. I'm not too familiar with MOP, and I've encountered something I don't understand, and I could use a theoretical explanation. Here is the module namespace::autoclean's documentation:
SYNOPSIS
package Foo;
use namespace::autoclean;
use Some::Package qw/imported_function/;
sub bar { imported_function('stuff') }
# later on:
Foo->bar; # works
Foo->imported_function; # will fail. imported_function got cleaned after compilation
So, back before I ever used Moose, the way that you called a method on an object was: the Perl interpreter would look up that method in the symbol table of the package that your object was blessed into (then, if not found, consider #ISA inheritance and the like). The way it called an imported function from within the package was: it looked up the name of the function in the symbol table of the package. As far as I've been aware to date, that means the same symbol table, either way, so this behavior should be impossible.
My initial inspection of the source was not productive. In broad terms, what is different when using Moose, MOP, and namespace::autoclean, that this sort of trickery becomes possible?
ed. To be especially clear, if I were to replace use namespace::autoclean with
CHECK { undef *Foo::imported_function }
then the Foo->bar; call described in the documentation would crash, because Foo->bar doesn't know where to find imported_function.
It's actually quite simple. For
some_sub()
some_sub is resolved at compile time. For
$o->some_method()
some_method is resolved at runtime. It cannot be done at compile-time since it depends on the value of $o.
There is nothing here that is non-standard. The line
use Some::Package qw/imported_function/;
imports imported_function into the current package, so Foo::imported_function is the same subroutine as Some::Package::imported_function. That assumes that Some::Package inherits from Exporter to do the necessary manipulation of the symbol tables.
The calls are method calls, so Foo->bar is the same as Foo::bar('Foo'). The only special thing here is that the magic that has been done by the import function from Exporter is undone at the end of compile time by namespace::autoclean.
I haven't looked at the code for this module, but since a package's symbol table is just a hash (known as a stash, for symbol table hash) it would be easy to preserve its state at one point and restore it afterwards. So I would guess namespace::autoclean takes a snapshot of the symbol table when it is loaded and the restores that state at the end of compilation time. This can conveniently be done in a CHECK block which behaves like a BEGIN block but is executed at the end of compilation and before the run starts.

Using use without package - big mess?

I have been USEing .pm files willy-nilly in my programs without really getting into using packages unless really needed. In essence, I would just have common routines in a .pm and they would become part of main when use'd (the .pm would have no package or Exporter or the like... just a bunch of routines).
However, I came across a situation the other day which I think I know what happened and why, but I was hoping to get some coaching from the experts here on best practices and how to resolve this. In essence, should packages be used always? Should I "do" files when I just want common routines absorbed into main (or the parent module/package)? Is Exporter really the way to handle all of this?
Here's example code of what I came across (I won't post the original code as it's thousands of lines... this is just the essence of the problem).
Pgm1.pl:
use PM1;
use PM2;
print "main\n";
&pm2sub1;
&pm1sub1;
PM1.pm:
package PM1;
require Exporter;
#ISA=qw(Exporter);
#EXPORT=qw(pm1sub1);
use Data::Dump 'dump';
use PM2;
&pm2sub1;
sub pm1sub1 {
print "pm1sub1 from caller ",dump(caller()),"\n";
&pm2sub1;
}
1;
PM2.pm:
use Data::Dump 'dump';
sub pm2sub1 {
print "pm2sub1 from caller ",dump(caller()),"\n";
}
1;
In essence, I'd been use'ing PM2.pm for some time with its &pm2sub1 subroutine. Then I wrote PM1.pm at some point and it needed PM2.pm's routines as well. However, in doing it like this, PM2.pm's modules got absorbed into PM2.pm's package and then Pgm1.pl couldn't do the same since PM2.pm had already been use'd.
This code will produce
Undefined subroutine &main::pm2sub1 called at E:\Scripts\PackageFun\Pgm1.pl line 4.
pm2sub1 from caller ("PM1", "PM1.pm", 7)
main
However, when I swap the use statements like so in Pgm1.pl
use PM2;
use PM1;
print "main\n";
&pm2sub1;
&pm1sub1;
... perl will allow PM2.pm's modules into main, but then not into PM1.pm's package:
Undefined subroutine &PM1::pm2sub1 called at PM1.pm line 7.
Compilation failed in require at E:\Scripts\PackageFun\Pgm1.pl line 2.
BEGIN failed--compilation aborted at E:\Scripts\PackageFun\Pgm1.pl line 2.
So, I think I can fix this by getting religious about packages and Exporter in all my modules. Trouble is, PM2.pm is already used in a great number of other programs, so it would be a ton of regression testing to make sure I didn't break anything.
Ideas?
See my answer to What is the difference between library files and modules?.
Only use require (and thus use) for modules (files with package, usually .pm). For "libraries" (files without package, usually .pl), use do.
Better yet, only use modules!
use will not load same file more than once. It will, however, call target package's import sub every time. You should format your PM2 as proper package, so use can find its import and export function to requestor's namespace from there.
(Or you could sneak your import function into proper package by fully qualifying its name, but don't do that.)
You're just asking for trouble arranging your code like this. Give each module a package name (namespace), then fully qualify calls to its functions, e.g. PM2::sub1() to call sub1 in package PM2. You are already naming the functions with the package name on them (pm2sub1); it is two extra characters (::) to do it the right way and then you don't need to bother with Exporter either.

Why don't Perl attribute handlers get called from other packages?

I am having a strange problem with Attribute::Handlers that looks like some kind of bug:
package MyPackage;
use Attribute::Handlers;
sub UNIVERSAL::foo :ATTR(CODE) {
...
}
When used in MyPackage, or from the main package of a script that uses MyPackage, the foo handler is called whenever the compiler comes across a function of the form
sub bar:foo {
...
}
However, I have another package, in a separate .pm file, that uses MyPackage. The compiler accepts the ":foo" attribute, but the handler is not called.
I tried writing an import function in MyPackage that exports the foo handler to the caller's namespace, but that doesn't seem to help.
Can anyone make sense of this? I've been racking my brain for the past few days over how to fix this.
By default, attribute handlers are called in the CHECK block after the compilation phase.
If the "using" package uses eval "use packagename"; then only BEGIN blocks will be executed. CHECK blocks won't be executed, and the attribute handlers won't be called.
Try using ATTR(CODE,BEGIN) to execute the handler in the BEGIN block.
I somehow totally missed the Attribute::Handlers in your post yesterday - as mentioned in my comment to the older version of this answer, perhaps wrapping the use MyPackage in a BEGIN block will cause things to be resolved properly.
I'm unsure as to why you chose to put the foo() attribute handler in UNIVERSAL - was that a step toward trying to get it to work?

Importing a require'd file as if it were a use statement

I am experiencing a problem with using a constant defined in a configuration file.
This is my package:
package myPackage;
require "APIconfig.pl";
APIconfig::import(APIconfig);
use constant SERVICE_URL => APIconfig::SERVICE_URL();
The configuration looks like this:
package APIconfig;
use constant SERVICE_URL => 'http://api.example.org/blah';
1;
When running this code, I get the following error:
Undefined subroutine &APIconfig::SERVICE_URL called at API.pl line 4.
I cannot use 'use' instead of 'require' because this expects the configuration file to be named .pm, and it's called .pl on a lot of servers on our network.
How can I use the package without renaming the file?
There are two differences between 'use' and 'require'. One of them affects your current problem, the other doesn't. Unfortunately you are working around one that has no effect.
The differences are:
1/ 'use' calls the import() function, 'require' doesn't.
2/ 'use' happens at compile time, 'require' happens at runtime.
You're working around the fact that 'require' doesn't call import() by calling it explicitly. This has no effect as your module doesn't export any symbols and doesn't have an import() subroutine.
You're not working around the fact that 'use' statements are executed at runtime. The problem is that "use constant SERVICE_URL => APIconfig::SERVICE_URL();" is executed at compile time and your 'require' hasn't run by then so myPackage knows nothing about APIconfig.
The (nasty, hacky) solution is to put the 'require' statement into a BEGIN block - to force it to be executed at compile time. You'll also want to remove the call to import() as that gives a runtime error (due to the absence of the subroutine).
The test files that I used to work this out are as follows:
$ cat APIconfig.pl
package APIconfig;
use constant SERVICE_URL => 'http://api.example.org/blah';
1;
$ cat api.pl
#!/usr/bin/perl
package myPackage;
BEGIN {
require "APIconfig.pl";
}
# APIconfig::import(APIconfig);
use constant SERVICE_URL => APIconfig::SERVICE_URL();
print SERVICE_URL, "\n";
$ ./api.pl
http://api.example.org/blah
The real solution is to rewrite APIconfig as a real module. You hint that you know that, but that environmental issues prevent you taking this approach. I highly recommend trying to work around those issues and doing things correctly.
That can't be possibly right - there is no subroutine import in package APIconfig. Once you're accessing symbolic names with a full package path, you don't need to export/import anyway.
The solution is to run require at compile time, before use constant. This works:
package myPackage;
BEGIN {
require "APIconfig.pl";
}
use constant SERVICE_URL => APIconfig::SERVICE_URL();
If it's a configuration file, don't make it code. I have a whole chapter in Mastering Perl about that, and there are many modules on CPAN to help you with almost any configuration format.
If it's code, why not just make it a module so you can use use. Modules are so much easier to control and manipulate within another program.
The easiest solutions are the ones where you don't swim against the tide. :)
Beyond that, use is the same as:
BEGIN {
require Module;
Module->import;
}
You just do the same thing with filename and the namespace it defines (as long as the code in the file looks like a module):
BEGIN {
require "file.pl"; # defines SomeNamespace
SomeNamespace->import;
}