Prototype mismatch error (perl) - perl

I am getting this strange error when importing a module I wrote into my Dancer app.
Prototype mismatch: sub main::from_json: none vs ($#) at mymodule.pm line 6.
Prototype mismatch: sub main::to_json: none vs ($#) at mymodule.pm line 6.
I guess this is because in my module I'm importing the perl JSON module.
Everything seems to perform fine, but I'm wondering what this error/warning is all about? I can't seem to find anything about it online.

Another situation where this arises is when some other module you have loaded defines a from_json/to_json. An example I've hit a couple times recently is with Dancer. If you have a package with
package Foo;
use Dancer qw/:syntax/;
use JSON;
1;
You will get that warning because (apparently) Dancer with the :syntax import puts a from_json and to_json into your namespace.
A quick solution in this situation is to just explicitly import nothing from JSON:
package Foo;
use Dancer qw/:syntax/;
use JSON qw//;
1;
Then in your code you will need to use the full package name to get JSON's subs, like this:
my $hash = JSON::from_json('{"bob":"sally"}');
In a situation like this, though, you want to use the full package names so it's clear which function you're getting--there are multiple declarations of to_json/from_json, so let's be very clear which one we mean.
If you put the following in Foo.pm and run with "perl Foo.pm", with and without the qw// after the use JSON, you can see how it works:
package Foo;
use Dancer qw/:syntax/;
use JSON qw//;
print Dumper( JSON::from_json('{"bob":"sally"}') ); use Data::Dumper;
1;

I believe Dancer/2 provides to_json and from_json to you, so you don't have to use JSON.
This will work:
use Dancer2 ':syntax';
get '/cheeseburgers' => {
return to_json($restaurant->make_cheeseburgers);
}

The reason I was getting this error was because in my own module, I was using the use directive and importing JSON and other modules BEFORE I declared my own package namespace, with
package mymodule
instead of AFTER. The package declaration has to come first.

See Prototypes in perlsub. The functions from_json and to_json were defined with different prototypes than used in the code.

Related

Cannot access function from perl module without using folder containing module identifier

I have a perl module named Mysql_Routines that contains various functions I use for manipulating mysql data with DBI. I export these functions as follows:
package Mysql_Routines;
use DBI;
use strict;
use warnings;
use Data::Dumper;
use Exporter qw(import);
our #EXPORT_OK = qw(connect_to insert_row get_rows);
These are accessed from other scripts and modules using the following code:
use my_modules::Mysql_Routines qw (connect_to insert_row get_rows);
This would all appear to be standard practice, as documented on Perl Maven. However, I can only then call these functions by using the module identifier or I get an error that it's an undefined subroutine. For example:
my $dbh = Mysql_Routines::connect_to('./config/mysql-local.conf');
works.
my $dbh = connect_to('./config/mysql-local.conf');
throws the following error:
Undefined subroutine &main::connect_to called
It's obviously not a huge issue, although I'd like to understand why this is happening, as I appear to have followed the correct guidelines for creating modules containing functions.
Please see my solution below. The package declaration should have included the top directory. Silly mistake.
You seem to be confused about the name of your module. Is it "Mysql_Routines" or "my_modules::Mysql_Routines"? I suspect that you want it to be called "Mysql_Routines", in which case your use my_modules::Mysql_Routines is rather unusual. Wny wouldn't you just have use Mysql_Routines?
I guess the answer is that your module lives in a directory called "my_modules". In which case, the correct approach would be to add that directory to your library search path. You could use code like:
use lib 'my_modules';
use Mysql_Routines';
I've discovered that the problem is that in the package declaration of the module I didn't include the top directory.
Changing package Mysql_Routines to package my_modules::Mysql_Routines solves the problem. With this solution the library search path does not need to be updated as was suggested as an alternative.

Subroutines defined in required file assigned to wrong namespace after use of custom module

In a script I am working on, I have something similar to the following:
require "environment.pm"; # Various definitions, including subroutine get_coll()
use Custom::Module;
In the Custom::Module file, I start with
package Custom::Module;
and end with
1;
When I try to call get_coll() I get an error about it:
( main::get_coll() ) being undefined.
If I require Custom::Module instead of using or change the call to be
Custom::Module::get_coll();
it works fine. This leads me to be believe that the "use" statement of CustomModule is changing the "active" namespace so when get_coll() is processed (since it is processed at the time of calling) it gets assigned to that namespace instead of main. This doesn't seem to be an issue with regular perl modules, but from the ones I've looked through, I haven't noticed anything different that would cause the namespace to "revert" back to main after the module has loaded. Any help in better understanding the namespace usage or fixing the module to not cause this problem would be greatly appreciated.
Side note: It isn't a huge issue for me to just "require" the module, but it was unexpected behavior to me so I mostly just want to better understand why what happened happened.
I've tried to recreate the files exactly as you describe them. Here are my three source files
You say
In a script I am working on, I have something similar to the following:
require "environment.pm"; # Various definitions, including subroutine get_coll()
use Custom::Module;
and
When I try to call get_coll() I get an error about it
Although you don't say where you're calling get_coll, I guess it's in the main script and I think that amounts to this script file
my_script.pl
use strict;
use warnings;
use 5.010;
require 'environment.pm';
use Custom::Module;
say get_coll();
and this module file
environment.pm
use strict;
use warnings;
use 5.010;
sub get_coll {
return 'coll';
}
1;
And then you say
In the Custom::Module file, I start with
package Custom::Module;
and end with
1;
So I wrote this module file. It doesn't have any contents because you didn't describe any
Custom/Module.pm
use strict;
use warnings;
use 5.010;
package Custom::Module;
1;
Now, when I run my_script.pl I get
coll
with no warnings or error messages, which is exactly as I expected
I am concerned that you say environment.pm contains get_coll, yet you are able to call Custom::Module::get_coll. Does Custom/Module.pm also have a require 'environment.pm'?
If you can point out where I have misinterpreted your description then please do, as I cannot replicate your problem at present and so am unable to help you
Otherwise, I recommend that you play with these three files to create a Short, Self-Contained, Correct Example of your problem. That will help us enormously to find a solution for you
You are mistaken about require being any different from use with respect to what namespace subroutines get defined in. It is not. And you are mistaken about use affecting the current package. It does not.
# Custom/Module.pm
package Custom::Module;
# the namespace is now "Custom::Module"
sub foo { ... } # defines &Custom::Module::foo
sub bar { ... } # defines &Custom::Module::bar
1; # end of Custom/Module.pm
---
# mainScript.pl
# without an explicit 'package' statement, we are in namespace "main"
use Custom::Module; # parses Custom/Module.pm
# but when the 'use' statement is complete, we are still in namespace "main"
sub baz { ... } # defines &main::baz
$x = baz(); # calls &main::baz
$y = foo(); # calls &main::foo, error if main::foo not defined
$z = Custom::Module::bar(); # calls &Custom::Module::bar
...
The comments describe what namespace we are in in each part of each file. None of that would be any different if we said require Custom::Module instead of use Custom::Module.
Now it can be a hassle to keep typing Custom::Module::bar() all the time when there is no main::bar() and there's no ambiguity about which bar subroutine you would be referring to. The key to getting perl to recognize your call to bar as referring to Custom::Module::bar is to copying the subroutine reference from Custom::Module into your current namespace. That is, making main::bar() refer to the same subroutine as Custom::Module::bar().
The canonical way to do this is with the Exporter module. The low level way to do this (and what Exporter does behind the scenes) is to manipulate perl's symbol tables.
For your specific problem, you would use Exporter like this:
# Custom/Module.pm
package Custom::Module;
use base 'Exporter'; # make Custom::Module inherit from Exporter
our #EXPORT = qw(foo bar);
sub foo { ... }
sub bar { ... }
...
1;
Now any other file that calls use Custom::Module will get the function get_coll imported into its namespace. This gets done behind the scenes in Exporter by manipulating the symbol table. Specifically, calling use Custom::Module from package main will get Exporter to make a typeglob assignment like
*main::foo = *Custom::Module::foo;
and this will make your function call from main::foo() invoke the code that was defined in Custom::Module::foo().

Prevent multiple inclusions in perl

Suppose I have two files: a module file that looks like this:
package myPackage;
use Bio::Seq;
and another file that looks like this:
use lib "path/to/lib";
use myPackage;
use Bio::Seq;
How can i prevent that Bio::Seq is included twice? Thanx
It won't be included twice. use semantics could be described like that:
require the module
call module's import
As the documentation says, it's equivalent to:
BEGIN { require Module; Module−>import( LIST ); }
require mechanism, on the other hand, assures modules' code is compiled and executed only once, the first time some require it. This mechanism is based on the special variable %INC. You can find further details in the documentation for use, require, and in the perlmod page.
use Foo
is mostly equivalent to
# perldoc -f use
BEGIN {
require "Foo.pm";
Foo->import();
}
And require "Foo" is mostly equivalent to
# perldoc -f require
sub require {
my ($filename) = #_;
if (exists $INC{$filename}) {
return 1 if $INC{$filename};
die "Compilation failed in require";
}
# .... find $filename in #INC
# really load
return do $realfilename;
}
So
No, the code won't be "Loaded" more than once, only "imported" more than once.
If you have code such as
package Bio::Seq;
...
sub import {
# fancy stuff
}
And you wanted to make sure a library was loaded, but not call import on it,
#perldoc -f use
use Bio::Seq ();
Modules aren't "included" in Perl like they are in C. They are "loaded", by which I mean "executed".
A module will only be loaded/executed once, no matter how many use statements specify it.
The only thing that happens for every use of a module is the call to the module's import method. That is typically used to export symbols to the using namespace.
I guess, you want to optimize the loading(usage) of Module.
For optimizing, dynamic loading may be helpful.
For dynamically loading a Perl Module, we use Class::Autouse.
For more details you can visit this link.
I guess the OP may look for a way of avoiding a long list of use statement boilerplate at the beginning of his/her Perl script. In this case, I'd like to point everyone to Import::Into. It works like the keyword import in Java and Python. Also, this blog post provides a wonderful demo of Import::Into.

Perl: Setup multiple package names for variable/functions?

First, I'd like to say this isn't a question of design, but a question of compliance. I'm aware there are issues with the current setup.
In a module, there are packages that are named after the servers, which has many of the same variables/functions that pertain to that server. It looks like this was set up so that you could do:
PRODUCTION_SERVER_NAME::printer() or
TEST_SERVER_NAME::printer()
Perhaps a better design might have been something like:
CENTRAL_PACKAGE_NAME::printer('production') or CENTRAL_PACKAGE_NAME::printer('test')
Anyhow, it seems the server names have changed, so instead of using the actual servernames, I'd like to rename the packages to just PRODUCTION or TEST, without changing the other code that is still refering to PRODUCTION_SERVER_NAME.
Something like:
package PRODUCTION, PRODUCTION_SERVER_NAME; # pseudo code
I'm guessing some sort of glob/import might work, but was wondering if there is already something that does something similar. I also realize it's not good practice to saturate namespaces.
I am not providing any comments on the design or anything that might involve changing client code. Functions in MyTest.pm can be accessed using either MyTest:: or MyExam::. However, you can't use use MyExam because the physical file is not there. You could do clever #INC tricks, but my programs always crash and burn when I try to be clever.
MyTest.pm
package MyTest;
sub hello { 'Hello' }
sub twoplustwo { 4 }
for my $sub (qw( hello twoplustwo)) {
no strict 'refs';
*{"MyExam::$sub"} = *{"MyTest::$sub"};
}
1;
test.pl
#!/usr/bin/env perl
use strict; use warnings;
use feature 'say';
use MyTest;
say MyExam::hello();
say MyExam::twoplustwo();
Output:
Hello
4
Have you considered using aliased? It sounds like it could work for you.
Try Exporter::Auto:
package Foo;
use Exporter::Auto;
sub foo {
print('foo');
}
package Bar;
use Foo;
package main;
Foo::foo();
Bar::foo();

How can I make a module that imports many modules for the user?

I have a rather complex data structure I've implemented in Perl. This has been broken up into about 20 classes. Basically, any time you want to use one of these classes, you need to use all of them.
Right now, if someone wants to use this data structure, they need to do something like:
use Component::Root;
use Component::Foo;
use Component::Bar;
use Component::Baz;
use Component::Flib;
use Component::Zen;
use Component::Zen::Foo;
use Component::Zen::Bar;
use Component::Zen::Baz;
... # 15 more of these...
use Component::Last;
to be able to manipulate all parts of it. How can I write a module that does this for the user, so all they have to do is
use Component;
to get all of the other modules imported?
In this particular case, the modules are all classes and don't have exports.
If these are just classes (i.e. they don't export any functions or variables when you use them), then all that really matters is that they have been loaded.
Just create Component.pm:
package Component;
our $VERSION = '1.00';
use Component::Root;
use Component::Foo;
use Component::Bar;
use Component::Baz;
use Component::Flib;
use Component::Zen;
use Component::Zen::Foo;
use Component::Zen::Bar;
use Component::Zen::Baz;
... # 15 more of these...
use Component::Last;
1; # Package return value
You don't need Exporter or anything like it.
However, instead of having a module that is nothing but use statements, it probably makes more sense to put those use statements into the class of the root node, or into the module that creates the data structure. That is, people will want to say:
use Component::Root;
my $root = Component::Root->new(...);
or
use Component qw(build_structure);
my $root = build_structure(...);
depending on how your data structure is normally created. It might be a bit confusing for people to write:
use Component;
my $root = Component::Root->new(...);
but it really depends on what your API looks like. If there are a number of classes that people might be calling new on, then use Component might be the way to go.
You could use the export_to_level method for all those packages that are Exporters.
MyPackage->export_to_level($where_to_export, $package, #what_to_export);
You could also just export all the symbols you import.
use PackageA qw<Huey Dewey Louie>;
...
our #ISA = qw<Exporter>; #inherit Exporter
our #EXPORT = qw<Huey Dewey Louie>;
However, if you don't want to export any symbols, and just want to load modules, then just include those use statements above, and any package in the process will be able to instantiate them as classes, say if they were all OO modules.
Provided that they have been loaded successfully, they will exist in %INC and the symbol table.
Moose::Exporter seems to do this, although all your other modules will have to use it as well.
In Component:
Moose::Exporter->setup_import_methods(
also => [qw/Component::Root Component::..*/],
);
If the modules do not export anything and don't have an import method (same requirements as cjm's answer) you just need to load the modules without import:
package Component;
our $VERSION = '1.00';
require Component::Root;
require Component::Foo;
require Component::Bar;
require Component::Baz;
require Component::Flib;
require Component::Zen;
require Component::Zen::Foo;
require Component::Zen::Bar;
require Component::Zen::Baz;
... # 15 more of these...
require Component::Last;
1; # Package return value
The users of the module will just do:
require Component;
If however some modules do exports, you will have to call their import method. So you have add an import method in your Component module that will call them:
sub import
{
Component::Root->import;
Component::Foo->import;
...
}
and so the module users will have to use it:
use Component;
Note that you may have to use some other tricks if the imported module has to insert symbols in the importer's context. See for example how the POE's import does it.
The Modern::Perl module touts itself with “enable all of the features of Modern Perl with one command,” where that command is
use Modern::Perl;
and those features are
For now, this only enables the strict and warnings pragmas, as well as all of the features available in Perl 5.10. It also enables C3 method resolution order; see perldoc mro for an explanation.
That's a lot for one line of code, which according to the perlmod documentation is exactly equivalent to
BEGIN { require Module; import Module; }
Consider Modern::Perl's implementation:
package Modern::Perl;
our $VERSION = '1.03';
use 5.010_000;
use strict;
use warnings;
use mro ();
use feature ();
sub import {
warnings->import();
strict->import();
feature->import( ':5.10' );
mro::set_mro( scalar caller(), 'c3' );
}
1; # End of Modern::Perl
To adapt this to your situation, from your top-level module use all the other modules you want to load, and call their imports, if any, from MyTopLevelModule::import.
Note that you don't necessarily need to copy
use 5.010_000;
into MyTopLevelModule.pm, but that would be a fine idea! According to the use documentation:
In the peculiar use VERSION form, VERSION may be either a positive decimal fraction such as 5.006, which will be compared to $], or a v-string of the form v5.6.1, which will be compared to $^V (aka $PERL_VERSION). An exception is raised if VERSION is greater than the version of the current Perl interpreter; Perl will not attempt to parse the rest of the file. Compare with require, which can do a similar check at run time.