• No results found

Introduction to Perl modules

N/A
N/A
Protected

Academic year: 2021

Share "Introduction to Perl modules"

Copied!
30
0
0

Loading.... (view fulltext now)

Full text

(1)

Introduction to Perl modules

Simon Whitaker

([email protected])

(2)

Evolving towards modularity

In its simplest form, programming in a

language like Perl involves writing lines of code that execute sequentially:

$name = "Alice";

print "Hello $name!\n";

# prints Hello Alice!

(3)

Evolving towards modularity

Writing line-by-line code works for simple tasks, but it can get unnecessarily repetitive:

$name = "Alice";

print "Hello $name!\n";

$name2 = "Bob";

print "Hello $name2!\n";

$name3 = "Charlie";

print "Hello $name3!\n";

(4)

Evolving towards modularity

Problems arise when I need to revise my code.

For example, imagine that I need to translate my program into French. I have to alter 3 lines of code:

$name = "Alice";

print "Bonjour $name!\n";

$name2 = "Bob";

print "Bonjour $name2!\n";

$name3 = "Charlie";

(5)

Evolving towards modularity

Better to encapsulate the repetitive stuff in a subroutine, which I only have to amend once:

sub greet {

print "Hello $_[0]\n";

}

$name = "Alice";

greet($name);

$name2 = "Bob";

(6)

Evolving towards modularity

And in French...

sub greet {

print "Bonjour $_[0]\n";

}

$name = "Alice";

greet($name);

$name2 = "Bob";

greet($name2);

(7)

Evolving towards modularity

I can now use greet() anywhere in my

program, making my code easier to maintain.

However, what if I want to use greet() in other programs? I can copy it into each

program, but then I have the same problem of having to maintain multiple instances of the

same code.

This is where modules come in.

(8)

What is a module?

A module is a library of Perl code that can be included in your Perl program.

When you include a Perl module in a program,

the functionality of that module is available for

you to use inside your own program.

(9)

Where do modules come from?

Perl modules come from a variety of sources:

• Standard modules: modules that are installed when you install Perl

• CPAN: the Comprehensive Perl Archive

Network – a global network of Perl module repositories

• Third parties: e.g. in-house code libraries,

Bioperl, etc

(10)

How to use a module

To include a module in your program, use Perl's use keyword. The general form is:

use Module;

Typically, the module will export its most

popular subroutines and variables into your

program. You can then use these subroutines

and variables just as if they were declared in

your program.

(11)

How to use a module

For example:

use Hello; # use the Hello module greet("Alice"); # greet() is exported

# by the Hello module

(12)

How to use a module

To use subroutines or variables that aren't

exported by default, precede their name with the module name followed by a double colon:

use Hello;

Hello::greet("Alice");

# calls greet() from the Hello module

(13)

How to use a module

Alternatively, you can state explicitly which variables and subroutines you want to export when you load the module, using the general form:

use Module qw( $variable subroutine );

where $variable and subroutine are the things you want to export. This form overrides the default form – only the variables and

subroutines you specify are imported.

(14)

Example 1: Text::Wrap

Text::Wrap is a simple but very useful module.

It's part of the standard module library, which means that it's installed when you install Perl.

Text::Wrap contains a subroutine called

wrap() (exported by default), which wraps text to form neat paragraphs.

wrap() takes three arguments: the indent string for the first line of a paragraph, the

indent string for subsequent lines, and the text

(15)

Example 1: Text::Wrap

use Text::Wrap;

$indent_first = " ";

$indent_subsq = "";

$text = "For the life of me I could

never understand why Mr Perkins didn't enjoy his job. He had everything a man could want: a place on the board, an absent boss and a cat named Henry.";

print wrap($indent_first,

(16)

Example 1: Text::Wrap

Output:

For the life of me I could never understand why Mr Perkins didn't enjoy his job. He had

everything a man could want: a place on the board, an absent boss and a cat named Henry.

(17)

Example 1: Text::Wrap

Text::Wrap also has a variable called

$columns , which determines how many columns my text wraps to. Unlike wrap(),

$columns isn't exported from Text::Wrap by default, so I refer to it here using its fully

qualified name:

# start of program as before

$Text::Wrap::columns = 20;

print wrap($indent_first,

(18)

Example 1: Text::Wrap

Output:

For the life of me I could never

understand why Mr Perkins didn't

enjoy his job. He had everything a man could want: a place on the board, an absent boss and

(19)

3 benefits of using modules

1. Saves time and effort 2. Greater portability

3. Modularity

(20)

Benefit 1: Saves time and effort

There are thousands of Perl modules out there, covering a huge range of common (and not so common) tasks. Don't re-invent the wheel!

If you need to grab data from a web page, create PDF files on the fly or connect to a

database from your Perl program, I have great

news for you – someone else has already done

the hard work. Better still, they'll share it with

you!

(21)

Benefit 2: Greater portability

Perl modules are generally written with

portability in mind. Again – let someone else do the hard work!

For example: imagine that you want to move a file from within your Perl program. Perl doesn't have a built-in move function, so you might be tempted to write:

`mv oldfile newfile`;

(22)

Benefit 2: Greater portability

This works fine – on UNIX. But if you try to run the program on Windows, or another operating system that doesn't have a mv command, it

fails.

This, however, is portable across OSs:

use File::Copy;

move("oldfile", "newfile");

(23)

Benefit 3: Modularity

As the name suggests, modules are modular!

With modules you can parcel bits of code that do specific tasks (e.g. wrapping text) into

discrete bundles, which can be re-used elsewhere.

If the code needs to be updated you only need to change the module, not dozens of Perl

programs.

(24)

A brief word about objects

From time to time you'll come across object- oriented (OO) Perl modules.

It's not important at this stage to understand much about OO programming or how it works, but it helps to be familiar with the syntax it

uses so that you feel comfortable using OO Perl

modules.

(25)

A brief word about objects

Objects represent complex entities, such as people, books or DNA sequences. Generally, you create objects using new:

$alice = new Student();

and interact with them using methods, which work just like subroutines:

print $alice->gradeAverage();

(26)

Example 2: Net::FTP

Net::FTP is an object-oriented Perl module that allows you to access FTP servers. As usual, you start by importing the module:

use Net::FTP;

Then you create a new Net::FTP object:

$ftp = new Net::FTP("ftp.mysite.com");

(27)

Example 2: Net::FTP

Now you can interact with your new object:

$ftp->login("username", "password");

$ftp->cwd("/pub");

$ftp->get("mrperkins.doc");

$ftp->quit();

(28)

Module documentation

When you install Perl modules, you get access to documentation for that module.

To read the documentation for a module, use the perldoc command:

$ perldoc File::Copy

Alternatively, on Unix you can use the man

command. On Windows you will have HTML

documentation available – there's a link in the

(29)

Further reading

For the official low-down on modules:

$ perldoc perlmod

For a list of standard modules:

$ perldoc perlmodlib

To read in the bath: Learning Perl Objects,

References & Modules by Randal L. Schwartz

(30)

Summary

• Modules are libraries of code that you can insert into your Perl programs

• Modules save you time and effort, by providing easy access to common tasks

• Use the perldoc command to get documentation on a Perl module

• Search CPAN for general-purpose modules

References

Related documents

The bit type will affect the size and quality of cuttings collected, and various hole conditions will dictate the types of sample we see at the surface..

The school will contact parents/carers of students who attend in incorrect uniform and, where possible, they will be asked to bring in the correct item of uniform or informed of

values of x close to 2, as we did in the previous sections. So it looks at least possible that indeed these values “approach” 1.41—already √ 2.001 is quite close. To compute an

(2007) noted that post-disaster reconstruction is quite similar to that of low-cost community housing projects in developing countries, but with added challenges.

Number of Wild Animal Parts and Products One Sale at Traditional African Medicine (Muthi) Shops (n ¼ 101) and Traditional Asian Medicine (TAM) Shops in South Africa (n ¼ 29) and

Tidak berpengaruhnya kesadaran merek terhadap keputusan pembelian disebabkan karena dalam pemilihan merek kosmetik, sebagian besar responden yang notabenenya adalah

The purpose of this paper is to apply the PMG-based error correction model and the panel differenced GMM Arellano-Bond estimation to investigate effects of fiscal deficit and broad

Our preferred definition of the dependent variable is the share of FDI attracted by a specific host country in total FDI flows from the source country under consideration to