开发者

How can I split my Perl code across multiple files?

开发者 https://www.devze.com 2023-01-29 14:03 出处:网络
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?

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

#i开发者_如何转开发nclude "foo.pl"
say_hello();

and:

# -> foo.pl
sub say_hello {print "hello!"}


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


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


put it in the same folder as your class and add use ClassName to the top of the calling file.

Also check the Perl OOP tutorial.

0

精彩评论

暂无评论...
验证码 换一张
取 消