Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I split my Perl code across multiple files?

Tags:

perl

My scripts are getting too long. How do I split my code (procedural subs) into multiple Perl files and tell the interpreter to make sense of them?

Kind of like:

# -> main.pl

#include "foo.pl"
say_hello();

and:

# -> foo.pl
sub say_hello {print "hello!"}
like image 277
hrealbkr Avatar asked Dec 06 '10 06:12

hrealbkr


2 Answers

What you want to do is create one or more modules. Start by looking over perlmod, especially the Perl Modules section.

Since you say you're writing procedural code, you'll want to export functions from your modules. The traditional way to do that is to use Exporter (which comes with Perl), although Sub::Exporter is a newer CPAN module that allows for some nice things. (See also its Sub::Exporter::Tutorial for an introduction to exporting functions.)

Modules can be placed in any of the directories listed in the @INC variable. Try perl -V to get a list. You can also use lib to add directories at runtime. One trick is to use the FindBin module to find the location of your script, and then add a directory relative to that:

use FindBin;                  # Suppose my script is /home/foo/bin/main.pl
use lib "$FindBin::Bin/lib";  # Add /home/foo/bin/lib to search path

Your sample code, converted to a module:
In main.pl:

#! /usr/bin/perl
use strict;
use warnings;
use Foo;
say_hello();

In Foo.pm:

package Foo;

use strict;
use warnings;
use Exporter 'import';
our $VERSION = '1.00';
our @EXPORT  = qw(say_hello);

sub say_hello {print "hello!"}

1; # A module must end with a true value or "use" will report an error
like image 64
cjm Avatar answered Oct 23 '22 11:10

cjm


I think you may be looking for do? http://perldoc.perl.org/functions/do.html

like image 31
Eaglebird Avatar answered Oct 23 '22 13:10

Eaglebird