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.
Related
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.
I need to import all our variables from the unnamed Perl module (Module.pm) and use them inside the Perl script (Script.pl).
The following code works well without the "use strict", but failed with it. How can I change this code to work with "use strict" without the manual listing of all imported variables (as described in the answer to other question)?
Thanks a lot for your help!
Script.pl:
use strict;
require Module;
print $Var1;
Module.pm:
our $Var1 = "1\n";
...
our $VarN = "N\n";
return 1;
Run the script:
$> perl Script.pl
Errors:
Global symbol "$Var1" requires explicit package name at Script.pl line 3.
Execution of Script.pl aborted due to compilation errors.
NOTE (1): The module is unnamed, so using a Module:: prefix is not the option.
NOTE (2): Module.pm contains also a set of functions configured by global variables.
NOTE (3): Variables are different and should NOT be stored in one array.
NOTE (4): Design is NOT good, but the question is not about the design. It's about forcing of the listed code to work with minimal modifications with the complexity O(1), i.e. a few lines of code that don't depend on the N.
Solution Candidate (ACCEPTED): Add $:: before all imported variables. It's compliant with strict and also allows to differ my variables from imported in the code.
Change your script to:
use strict;
require Module;
print $Module::Var1;
The problem is the $Var1 isn't in the main namespace, it's in Module's namespace.
Edit: As is pointed out in comments below, you haven't named your module (i.e. it doesn't say package Module; at the top). Because of this, there is no Module namespace. Changing your script to:
use strict;
require Module;
print $main::Var1;
...allows the script to correctly print out 1\n.
If you have to import all the our variables in every module, there's something seriously wrong with your design. I suggest that you redesign your program to separate the elements so there is a minimum of cross-talk between them. This is called decoupling.
You want to export all variables from a module, and you want to do it in such a way that you don't even know what you're exporting? Forget about use strict and use warnings because if you put them in your program, they'll just run screaming out, and curl up in a corner weeping hysterically.
I never, and I don't mean hardly ever, never export variables. I always create a method to pull out the required value. It gives me vital control over what I'm exposing to the outside world and it keeps the user's namespace pure.
Let's look at the possible problems with your idea.
You have no idea what is being exported in your module. How is the program that uses that module going to know what to use? Somewhere, you have to document that the variable $foo and #bar are available for use. If you have to do that, why not simply play it safe?
You have the issue of someone changing the module, and suddenly a new variable is being exported into the program using that module. Imagine if that variable was already in use. The program suddenly has a bug, and you'll never be able to figure it out.
You are exporting a variable in your module, and the developer decides to modify that variable, or even removes it from the program. Again, because you have no idea what is being imported or exported, there's no way of knowing why a bug suddenly appeared in the program.
As I mentioned, you have to know somewhere what is being used in your module that the program can use, so you have to document it anyway. If you're going to insist on importing variables, at least use the EXPORT_OK array and the Exporter module. That will help limit the damage. This way, your program can declare what variables its depending upon and your module can declare what variables it knows programs might be using. If I am modifying the module, I would be extra careful of any variable I see I am exporting. And, if you must specify in your program what variables you're importing, you know to be cautious about those particular variables.
Otherwise, why bother with modules? Why not simply go back to Perl 3.0 and use require instead of use and forget about using the package statement.
It sounds like you have data in a file and are trying to load that data into your program.
As it is now, the our declarations in the module only declare variables for the scope of that file. Once the file finshes running, to access the variables, you need to use their fully qualified name. If your module has a package xyz; line, then the fully qualified name is $xzy::Var1. If there is no package declaration, then the default package main is used, giving your variables the name $main::Var1
However, any time that you are making many variables all with numeric name changes, you probably should be using an array.
Change your module to something like:
#My::Module::Data = ("1\n", "2\n" ... )
and then access the items by index:
$My::Module::Data[1]
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'.
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...
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.)