perltutorial Juerd <h2>No include</h2> <p> Some simple languages, like PHP, offer an <tt>include()</tt> to include a file literally. Perl does not. Then how can you still load code from other files? </p> <p> There are many ways to do this in Perl, but there is no easy way to get close to what most people expect of an <tt>include()</tt>. People who want to include files usually come from simpler languages, or have no programming experience at all. The hardest thing they will have to learn is that <b>you should not want to include a file</b>. </p> <p> That may sound harsh, but it's a Perl reality. In Perl, we don't include or link libraries and code reuse isn't usually done by copying and pasting. Instead, Perl programmers use <b>modules</b>. The keywords [use] and [require] are meant for use with modules. Only in the simplest of situations you can get away with abusing [require] as if it were some kind of <tt>include()</tt>, but it's easy to get bitten by how it works: it only loads any given file <b>once</b>. </p> <h2>Creating a module</h2> <p> What is a module, anyway? [perlmod] defines it as: <em>just a set of related functions in a library file, i.e., a Perl package with the same name as the file.</em> </p> <p> Creating a module is EASY, but it is a little more work than just creating a file with code in it. First, you need to think of a module name. This is the basis for both the filename and the package name, and these have to be synchronised for some features to work. For project specific modules, I always create a new top-level namespace with the name of the project. For example, <tt>NameOfTheProject/</tt> is a good filename (in real life, use something a little more meaningful). The corresponding package is <tt>NameOfTheProject::SomeModule</tt>. Use CamelCaps like this, because everyone else does too. </p> <p> The file must be in a directory that is listed in <tt>@INC</tt>. To find out what your <tt>@INC</tt> is, run <tt>perl -V</tt>. The current working directory (listed as its symbolic name <tt>.</tt> (a single dot)) should be listed. To begin with, putting the module in the script's directory is a good idea. It is the easiest way to keep things organized. If you want to put the module somewhere else, you will have to update <tt>@INC</tt>, so that perl knows where to find it. An easy way to do get code like this in the main script: <code> use lib 'path/to/the/modules'; # The example module could be path/to/the/modules/NameOfTheProject/ </code> </p> <p> What goes in the module itself doesn't require much explanation. I'll just give a complete example of a simple NameOfTheProject::SomeModule: <code> use strict; package NameOfTheProject::SomeModule; sub some_function { # put sane code here return 123; } 1; </code> Just list all the subs as you usually would, put a [package] statement at the top and a true value at the bottom (<tt>1</tt> will suffice). Obviously, [use] [strict] is a good idea. You should never code a module that does not have this. Beware: A <tt>use strict;</tt> statement in the main script has no effect on the module. </p> <p> A module runs only once. That means that for code to be reusable, it <b>must</b> be in a sub. In fact, it's considered very bad style to do anything (except declaring and initializing some variables) in the module's main code. Just don't do that. </p> <p> You can now load the module and use its sub, simply by doing: <code> use NameOfTheProject::SomeModule; print NameOfTheProject::SomeModule::some_function(); # prints 123 </code> </p> <p> You can have the module export its sub(s) to the caller's namespace (that is: the package the [use] statement is in. By default, this is <tt>main</tt>). For this, put after the [package] statement: <code> use base 'Exporter'; our @EXPORT_OK = ('some_function'); </code> Then, when [use]ing the module, you can request that <tt>some_function</tt> be imported to your namespace with: <code> use NameOfTheProject::SomeModule ('some_function'); print some_function(); # prints 123 </code> To have it exported automatically, use <tt>@EXPORT</tt> instead of <tt>@EXPORT_OK</tt>. This will eventually bite you if the function names are generic. For example, many people get bitten by [cpan://LWP::Simple]'s <tt>get</tt> function. It is not unlikely that you already have one. </p> <p> There are more ways to export functions. I of course prefer to use my own module [cpan://Exporter::Tidy]. Not only because it's smaller and often faster, but mostly because it lets the user of a module define a prefix to avoid clashes. Read its documentation for instructions. </p> <p> For the export/import mechanism, it is very important that the filename, the package name and the name used with [use] are equal. This is case sensitive. (Ever wondered why under Windows, <tt>use Strict;</tt> doesn't enable [strict], but also doesn't emit any warning or error message? It has everything to do with the case insensitive filesystem that Windows uses.) </p> <h2>Stubbornly still wanting to include</h2> <p> Sometimes, a module just isn't logical. For example, when you want to use an external configuration file. (Many beginners and people who post code online put configuration in the script itself for ease of use, but this makes upgrading the script harder.) There are many configuration file reader modules you can use, but why use one of those if you can just use bare Perl? </p> <p> This is where [do] comes in. What [do] does is very close to what an [include] would do, but with a very annoying exception: the new file gets its own lexical scope. In other words: a variable declared with [my] is not accessible externally. This follows all logical rules attached to lexical variables, but can be very annoying. Fortunately, this does not have to be a problem. [do] returns whatever the included script returned, and if you make that script just the contents of a hash, here's my favourite way to offer configurability: <code> # This is mirror => '', path => '/var/www/example', skip_files => [ 'png', 'gif', 'jpg' ], </code> (The last <code>,</code> is optional, but it's included to make adding a line easier.) <code> # This is use strict; my %config = do ''; chdir $config{path}; ... </code> Error checking is left as an excercise. </p> <p> Because we used only the return value of the script, and never even touched a variable in <tt></tt>, the inaccessibility of lexical variables is no longer a problem. Besides that, the code looks very clean and we have a very powerful config file format that automatically supports comments and all kinds of useful functions. How about <tt>interval => 24 * 60 * 60,</tt> for self-documentation? :) </p> <h2>Still not good enough</h2> <p> [do] updates <tt>%INC</tt>, which you may or may not want. To avoid this, use [eval] [cpan://File::Slurp|read_file] instead. To find out if you want this, read [perlvar]. </p> <p> There is a way to get an <tt>include()</tt> the way other languages have it. This is a very ugly hack that uses an internal exception made for Perl's debugger, and is possibly not future proof. As said before, you should not want to include a file. Still, because it is possible, I feel I have to tell you how. Just don't actually use it. </p> <p> If you read the documentation for [eval] (which you of course should (don't use an operator without having read its documentation first)), you see that if it is called from within the <tt>DB</tt> package, it is executed in the caller's scope. This means that lexical values are made visible and the file behaves as a code block. </p> <p> Here is an example to get an <tt>include()</tt> function that actually works the way most people expect: <code> use strict; package Acme::Include; use base 'Exporter'; use File::Slurp (); our @EXPORT = 'include'; { package DB; # The sub's name is fully qualified to avoid getting a B::Include sub Acme::Include::include ($) { my ($filename) = @_; my $code = qq[#line 1 "$filename"\n] . File::Slurp::read_file($filename); eval $code; } } 1; </code> Documentation for the <tt>#line</tt> directive is in [perlsyn]. </p> <p> To test this new module, save it as Acme/ and create: <code> # This is use strict; use Acme::Include; my $lexical = 'set in'; include ''; print $lexical; # Should print: set in </code> and: <code> # This is use strict; $lexical = 'set in'; # There is no "my" here, because that would create a *new* lexical # variable, hiding the existing one. </code> and then run <tt>perl</tt>. </p> <p> This example Acme::Include does not have any error checking. In practice, you will want to check <tt>$@</tt> somewhere (but you also want to retain the value returned by the included file, and context to propagate properly. Good luck!). </p> <h2>Learning more</h2> <p> I wrote this tutorial to have an answer ready for the <i>n</i>th time someone in EFnet's #perlhelp asks why [require] works only once, or asks how to really include a file. Explaining the same thing over and over gets annoying over time. This is not a good guide to writing modules. For that, read chapter 10 of [|Beginning Perl] and [perlmod] and [perlnewmod]. Of course, good code always comes with good documentation; so learn [id://252477]. </p> <h2>One last thing</h2> <p> If you name your module <tt>Test</tt>, don't be surprised if it doesn't work. The current working directory comes <b>last</b> in <tt>@INC</tt>, so the [perldoc://Test] module that is in the Perl distribution is probably loaded instead. This bites me at least once per year, this time while writing this tutorial :). </p>