How do I use Perl's import, use, require and do? - perl

Can someone explain exactly the usage recomandations regarding the 4 perl imports: do, import, use and require?
I'm looking for practical recommendations and keeping in mind possible issues that might arise in the context of mod_perl or something similar.
We all love simple examples, good ones!
So far the best resource I found was http://soniahamilton.wordpress.com/2009/05/09/perl-use-require-import-and-do/ , but this missed to consider the implications of mod_perl.

You should first read perldoc -f use and perldoc -f require.
They are excellent resources and explain how use works, how it invokes import and then require, and how you could theoretically implement require in terms of do.
If you have already read them, do you still have any specific open questions that the standard documentation doesn't cover well enough and you would like to have answered in more detail?

do will call the code, no ifs, ands, or buts, at runtime. This is usually a bad idea, because if that's happening, you should really probably be putting it into a subroutine.
require will call exactly once and then no more, at runtime. it can do it for a package, too, in which case it will actually go find that package for you.
use does everything require does in the package case, then calls import in that package.
import is a function defined in a package. it gets called by use, but it's not otherwise special.

You can look at the mod_perl documentation for use(), require(), do()

Since this question didn't gather more than RTFM as an 'answer':
Create a file called Example.pm in the same directory (or relative, like ./lib) and add these lines
package Example;
use Exporter qw(import);
our #EXPORT_OK = qw(subroutine1 subroutine2 etc)
1;
In your main script add these lines
use lib '.';
use Example qw(subroutine1 subroutine2 etc);
Subroutines named in both export_ok and use qw lists are available in the main script.
Bart...

Related

Use or not to use the namespace::sweep and/or Modern::Perl

In my last question #Borodin commented my question with:
You should start by removing Modern::Perl and namespace::sweep.
Modules that behave as pragma should be avoided.
I'm confused a bit, because:
in the LATEST Moose BestPractices manual recommending to use namespace::autoclean.
The use namespace::autoclean bit is simply good code hygiene, as it
removes imported symbols from your class's namespace at the end of
your package's compile cycle, including Moose keywords. Once the class
has been built, these keywords are not needed. (This is preferred to
placing no Moose at the end of your package).
In the Book Intermediate perl recommending to use the namespace::autoclean too.
Yes, I'm used the instead of the autoclean the sweep module - because again from the doccu
This pragma was written to address some problems with the excellent
namespace::autoclean. In particular, namespace::autoclean will remove
special symbols that are installed by overload, so you can't use
namespace::autoclean on objects that overload Perl operators.
...
...
In most cases, namespace::sweep should work as a drop-in replacement
for namespace::autoclean. Upon release, this pragma passes all of
namespace::autoclean's tests, in addition to its own.
And because I'm an perl beginner, i'm really confused. For me, when i reading: this module addressing some problems of another module - mean: use this one.
'Manual (where from I should learn) says "use it" and expert from stackoverflow teling: don't use it.
So please, can someone explain me:
it is correct to use namespace::sweep or I should use namespace::autoclean or none of them?
if none, why the BestPractices recommends it?
For the `ModernPerl'. Sure, I'm probably don't understand deeply and "exactly" what is does. What i know, (again from it's doccu)
This 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 as documented in perldoc mro and loads IO::File and IO::Handle
so that you may call methods on filehandles. In the future, it may
include additional core modules and pragmas.
Sure, don't deeply understand to mro, only think it is an answer to the "deadly diamond of death" problem in cases of multiple inheritance.
Up to today, i was really happy with it, because it is shorting for me the needed pragmas:
use strict;
use warnings;
use feature 'say';
So, what is a "status" of the "Modern::Perl" (and other similar cpanm modules)? Allowed to use, or not?
On your question about namespace::sweep:
Firstly, take note of the actual problem that namespace::sweep resolves.
In particular, namespace::autoclean will remove special symbols that are installed by overload, so you can't use namespace::autoclean on objects that overload Perl operators.
What this means is that if your class has overloaded operators they won't work if you also use namespace::autoclean. But this problem only occurs if you use overload. Other than that, namespace::autoclean will suffice.
Secondly, it says that namespace::sweep can be used instead of namespace::autoclean:
In most cases, namespace::sweep should work as a drop-in replacement for namespace::autoclean. Upon release, this pragma passes all of namespace::autoclean's tests, in addition to its own.
So to answer your question, "is it correct to use namespace::sweep or I should use namespace::autoclean or none of them?"
You should use at least one of them as recommended by Moose Best Practices.
It is generally ok to use namespace::sweep since it says it is designed to do so and it passes all of namespace::autoclean's tests.
In spite of point 2 above, if you don't use overload then you don't have a problem with using namespace::autoclean, so you could just use that in this case.
Specifying use 5.014; (or other version >= 5.011) will automatically do use strict; and enable all features of that version for you; IMO this is some of the reason Modern::Perl has not gained a whole lot of traction.
I've always disliked Modern::Perl because it doesn't describe what it does; it is someone else's idea of "modern" as of some fixed point in the past.

Exporting symbols without Exporter

I am learning how to use packages and objects in Perl.
It has been suggested that I use Exporter in order to use the functions and variables of a module that have the package directive.
I was curious to know whether there is a way to export symbols without using Exporter? In other words, can Exporter be emulated in some way?
The reason I ask is due to my assumption that Exporter carries extra overhead for functionality that small, simple scripts that must run as fast as possible don't need, and could be avoided by including that functionality with a few simple lines of code.
Maybe a simple illustration of what I mean might help.
Say I have a module which only does this
my $my_string = "my_print";
sub my_print {
print "$my_string: ", #_;
}
which would allow for a lot of small scripts to use my_print instead of print, with just a simple require with the filename of my module (and very little overhead).
Then, I wanted to use this in another module that has a package declaration, and this no longer works, so now I must use a package declaration and therefore Exporter in my simple module just to get this to work in the new module.
Having been using Perl for quite a while I am used the fact that almost everything is quite simple, straightforward, and low overhead, so I just feel that there could be such a solution for this. If not, then I would accept an answer that explains exactly why Exporter is the only way.
What Exporter does is quite simple. Here's how you can do it without using Exporter:
In Foo.pm:
package Foo;
use strict;
use warnings;
sub answer { 42 }
sub import {
no strict 'refs';
my $caller = caller;
*{$caller . "::answer"} = \&answer;
}
1;
In script.pl:
use Foo;
print answer(), "\n";
However, as others have said, you really needn't worry about the overhead of using Exporter. It's a fairly small and efficient module, and has been bundled with every version of Perl since 5.0. Whatsmore, chances are you're already loading it somewhere anyway -- many of the core Perl modules (such as Carp, Scalar::Util, List::Util, etc) use it.
Update: in an earlier version of the code above, I forgot the no strict 'refs';. This is necessary for *{$some_string} to work.
Exporter is definitely low overhead. There is also a list of alternative modules in the See Also section.
If you're curious, you can do a search on CPAN for the module and view the source yourself. You'll notice that the majority of the "code" is just documentation. However, honestly if you're this new to perl, you shouldn't be worrying about streamlining your code for being light weight as much as you should be aiming to take advantage of as many resources as possible to make coding quicker and easier.
Just my $.02
It sounds very much like you're trying to find an excuse to avoid Exporter? Have you really had programs that start up too slowly? Exporter is loaded and executed only in the compilation phase.
If you are genuinely worried about compilation speed then you should write
BEGIN { require MyPackage }
and then later
MyPackage::myprint($myparam)
which involves no overhead from Exporter at all, or even from the equivalent in-line code.
Yes, the code that actually exports symbols from one package to another is just a single line in the code of Exporter.pm and you could duplicate it. But wouldn't you much rather just add
use MyPackage;
at the start of you program and know that, from any context, the symbols from MyPackage would be correctly exported?
If you have "small simple scripts that must be run as fast as possible" then you should investigate leaving them running as daemons rather than recompiling the Perl each time the program is run.

Should Perl boilerplate go before or after a package declaration?

Assuming there's only one package in a file, does the order or the following Perl boilerplate matter? if there are no technical reasons are there any aesthetic?
use 5.006;
use strict;
use warnings;
package foo;
The order matters if any part of your boiler plate imports any subroutines or variables, or does anything tricky with the caller's namespace.
If you get into the habit of placing it before the package name, then one day when you want to add use List::Util 'reduce'; to your boiler plate, the subroutine will be imported into main instead of foo. So package foo will not have reduce imported, and you may be scratching your head for a while trying to figure out why it isn't working.
The reason why it doesn't matter with the three imports you have shown is that they are all pragmatic modules (or assertions), and their effect is lexically scoped, not package scoped. Placed at the top of the file, those pragmas will be in effect for the entire file.
The order doesn't matter from a technical standpoint.
It's always been my practice (and, fwiw, what's used in Perl Best Practices) to put the package declaration at the very start. I'd suggest a blank line before the package declaration if there's anything before it, to make it stand out.

Old .pl modules versus new .pm modules

I'm a beginner in Perl and I'm trying to build in my head the best ways of structuring a Perl program. I'm proficient in Python and I'm used to the python from foo import bar way of importing functions and classes from python modules. As I understood in Perl there are many ways of doing this, .pm and .pl modules, EXPORTs and #ISAs, use and require, etc. and it is not easy for a beginner to get a clear idea of which are the differences, advantages and drawbacks of each (even after reading Beginning Perl and Intermediate Perl).
The problem stated, my current question is related to a sentence from perldoc perlmod:
Perl module files have the
extension .pm. The use operator
assumes this so you don't have to
spell out "Module.pm" in quotes. This
also helps to differentiate new
modules from old .pl and .ph files.
Which are the differences between old .pl way of preparing modules and the new .pm way?
Are they really the old and the modern way? (I assume they are because Perlmod says that but I would like to get some input about this).
The use function and .pm-type modules were introduced in Perl 5, released 16 years ago next month. The "old .pl and .ph files" perlmod is referring to were used with Perl 4 (and earlier). At this point, they're only interesting to computer historians. For your purposes, just forget about .pl libraries.
Which are the differences between old .pl way of preparing modules and the new .pm way?
You can find few old modules inside the Perl's own standard library (pointed to by #INC, the paths can be seen in perl -V output).
In older times, there were no packages. One was doing e.g. require "open2.pl"; which is analogous to essentially including the content of file as it is in the calling script. All functions declared, all global variables were becoming part of the script's context. Or in other words: polluting your context. Including several files might have lead to all possible conflicts.
New modules use package keyword to define their own context and name of the namespace. When use-ed by a script, new modules have possibility to not import/add anything to the immediate context of the script thus prevent namespace pollution and potential conflicts.
#EXPORT/#EXPORT_OK lists are used by standard utility module Exporter which helps to import the module functions into the calling context: so that one doesn't have to write all the time full name of the functions. The lists are generally customized by the module depending on the parameter list passed to the use like in use POSIX qw/:errno_h/;. See perldoc Exporter for more details.
#ISA is a Perl's inheritance mechanism. It tells Perl that if it can't find a function inside of the current package, to scan for the function inside all the packages mentioned in the #ISA. Simple modules often have there only the Exporter mentioned to use its import() method (what is also well described in the same perldoc Exporter).
Reusing code by creating .pl files (the "pl" actually stands for "Perl library") was the way that it was done back in Perl 4 - before we had the 'package' keyword and the 'use' statement.
It's a nasty old way of doing things. If you're coming across documentation that recommends it then that's a strong indication that you should ignore that documentation as it's either really old or written by someone who hasn't kept up to date with Perl development for over fifteen years.
For some examples of the different ways of building Perl modules in the modern way, see my answer to Perl Module Method Calls: Can't call method “X” on an undefined value at ${SOMEFILE} line ${SOMELINE}
I don't know nothing about .pl rather modules rather than they did exist some time ago, nobody seems to use them nowadays so you proably shouldn't use them either.
Stick to pm modules, ignore #ISA right now, that's for OOP. Export isn't that important either, because you can always call your methods fully quallified.
So rather than writing this:
file: MyPkg.pm
package MyPkg;
#EXPORT = qw(func1 func2);
sub func1 { ... };
sub func2 { ... };
file: main.pl
#!/usr/bin/perl
use strict;
use warnings;
use MyPkg;
&func1();
you should, for the beginning, write that:
file: MyPkg.pm
package MyPkg;
sub func1 { ... };
sub func2 { ... };
file: main.pl
#!/usr/bin/perl
use strict;
use warnings;
use MyPkg;
&MyPkg::func1();
And later when you see which methods should really be exported you can do that without having to change your exisiting code.
The use loades your module and call import, which would make any EXPORTed subs avalable in your current package. In the seconds example a require would do, which doesn't call import, but I tend to always use 'use'.

What's the best way to have two modules which use functions from one another in Perl?

Unfortunately, I'm a totally noob when it comes to creating packages, exporting, etc in Perl. I tried reading some of the modules and often found myself dozing off from the long chapters. It would be helpful if I can find what I need to understand in just one simple webpage without the need to scroll down. :P
Basically I have two modules, A & B, and A will use some function off from B and B will use some functions off from A. I get a tons of warning about function redefined when I try to compile via perl -c.
Is there a way to do this properly? Or is my design retarded? If so what would be a better way? As the reason I did this is to avoid copy n pasting the other module functions again into this module and renaming them.
It's not really good practice to have circular dependencies. I'd advise factoring something or another to a third module so you can have A depends on B, A depends on C, B depends on C.
So... the suggestion to factor out common code into another module is
a good one. But, you shouldn't name modules *.pl, and you shouldn't
load them by require-ing a certain pathname (as in require
"../lib/foo.pl";). (For one thing, saying '..' makes your script
depend on being executed from the same working directory every time.
So your script may work when you run it as perl foo.pl, but it won't
work when you run it as perl YourApp/foo.pl. That is generally not good.)
Let's say your app is called YourApp. You should build your
application as a set of modules that live in a lib/ directory. For
example, here is a "Foo" module; its filename is lib/YourApp/Foo.pm.
package YourApp::Foo;
use strict;
sub do_something {
# code goes here
}
Now, let's say you have a module called "Bar" that depends on "Foo".
You just make lib/YourApp/Bar.pm and say:
package YourApp::Bar;
use strict;
use YourApp::Foo;
sub do_something_else {
return YourApp::Foo::do_something() + 1;
}
(As an advanced exercise, you can use Sub::Exporter or Exporter to
make use YourApp::Foo install subroutines in the consuming package's
namespace, so that you don't have to write YourApp::Foo:: before
everything.)
Anyway, you build your whole app like this. Logical pieces of
functionally should be grouped together in modules (or even better,
classes).
To make all this run, you write a small script that looks like this (I
put these in bin/, so let's call it bin/yourapp.pl):
#!/usr/bin/env perl
use strict;
use warnings;
use feature ':5.10';
use FindBin qw($Bin);
use lib "$Bin/../lib";
use YourApp;
YourApp::run(#ARGV);
The key here is that none of your code is outside of modules, except a
tiny bit of boilerplate to start your app running. This is easy to
maintain, and more importantly, it makes it easy to write automated
tests. Instead of running something from the command-line, you can
just call a function with some values.
Anyway, this is probably off-topic now. But I think it's important
to know.
The simple answer is to not test compile modules with perl -c... use perl -e'use Module'
or perl -e0 -MModule instead.
perl -c is designed for doing a test compile of a script, not a module. When you run it
on one of your
When recursively using modules, the key point is to make sure anything externally referenced is set up early. Usually this means at least making use #ISA be set in a compile time construct (in BEGIN{} or via "use parent" or the deprecated "use base") and #EXPORT and friends be set in BEGIN{}.
The basic problem is that if module Foo uses module Bar (which uses Foo), compilation of Foo stops right at that point until Bar is fully compiled and it's mainline code has executed. Making sure that whatever parts of Foo Bar's compile and run-of-mainline-code
need are there is the answer.
(In many cases, you can sensibly separate out the functionality into more modules and break the recursion. This is best of all.)