Perl: How to Write a Module

By Xah Lee. Date: . Last updated: .

Here's to write a module in Perl by a example.

Save the following 3 lines in a file and name it

# -*- coding: utf-8 -*-
# perl

package mymodule;    # declaring the module

sub f1($){$_[0]+1}  # module body

# more code here

1                               # module must return a true value

Then, call it like the following way:

# -*- coding: utf-8 -*-
# perl

use mymodule;            # import the module
print mymodule::f1(5);   # call the function

This is the simplest illustration of writing a package in Perl and calling its function.

Module vs Package

A “module” is simply a file of Perl code. To load a module, use require name;.

package is a Perl keyword. When a file has declaration package name;, it creates its own namespace, and the file must must return a value true (any number, string, as the last line will do).

Basically, all Perl modules intended to be used as library, are declared as packages.

The word “module” and “package” are often used interchangably to mean “library”. Sometimes in a technical context, the word “module” refers to a file, and the word “package” refers to the namespace.

Module File Path Correspondence

Module/package name corresponds to the file's name/path. For example, if you have a module at

you load it like this:

use abc;

module file can be grouped into directories. If you have a module with subdirs, named:


you can load it like this

use GameX::sound;

The double colon :: corresponding to directory separator /.

If you have a question, put $5 at patreon and message me.


  1. Perl Overview
  2. Version String
  3. Help System


  1. Quoting String
  2. Format String
  3. String Operations
  4. True, False
  5. if then else
  6. Loop
  7. List / Array
  8. Loop Thru List
  9. Map f to List
  10. List Comprehension
  11. Hash Table
  12. Function Optional Param
  13. regex
  14. Split Line by Regex


  1. Sort List, Matrix, Object
  2. Sort Matrix
  3. List Modules, Search Paths
  4. Write a Module
  5. Read / Write File
  6. Traverse Dir
  7. Find / Replace
  8. Complex Numbers
  9. System Call
  10. Compress / Decompress gzip
  11. Get Env Var
  12. GET Web Content
  13. Unicode 🐪
  14. Convert File Encoding
  15. Sort Unstable