How to Install Perl on Ubuntu

Perl is a high-level, general-purpose programming language designed for text processing, system administration, web development, and network programming. Whether you need to automate log parsing, build CGI scripts, or manage system configurations, Perl provides powerful pattern matching and a vast module ecosystem through CPAN. This guide covers two installation methods: using Ubuntu’s default APT repository for a stable, distribution-tested version, or compiling from source for the latest features and optimizations.

Choose Your Perl Installation Method

Ubuntu offers multiple ways to install Perl, each suited to different needs. The following table compares the available methods covered in this guide:

MethodChannelVersionUpdatesBest For
APT Package ManagerUbuntu ReposDistribution defaultAutomatic via apt upgradeMost users who prefer stability and easy maintenance
Source CompilationPerl.orgLatest stableManual recompilationDevelopers needing specific versions or latest features

For most users, the APT method is recommended because it provides automatic security updates and integrates cleanly with Ubuntu’s package management. Only compile from source if you specifically need features unavailable in the repository version or require a particular Perl release.

Ubuntu includes a minimal Perl interpreter (perl-base) by default, which many system tools depend on. The APT method installs the full Perl package with additional modules and documentation. Commands shown work identically on all supported Ubuntu LTS releases.

Method 1: Install Perl via APT

Check Existing Perl Installation

Before installing, verify whether the full Perl package is already present on your system. Since the minimal perl-base package is pre-installed on Ubuntu, you will see version output even on fresh systems. However, this minimal installation lacks many modules and documentation included in the full package.

perl -v

If Perl is installed, you will see version information similar to the following:

This is perl 5, version 40, subversion 1 (v5.40.1) built for x86_64-linux-gnu-thread-multi
(with 48 registered patches, see perl -V for more detail)

Copyright 1987-2024, Larry Wall

The version number varies by Ubuntu release: Ubuntu 26.04 includes Perl 5.40, Ubuntu 24.04 includes Perl 5.38, and Ubuntu 22.04 includes Perl 5.34. All versions are fully functional for most use cases.

Update Package Repository

First, refresh your package index to ensure you install the latest available version from Ubuntu’s repositories:

sudo apt update

Install Perl Package

Next, install the full Perl package, which includes the interpreter, core modules, and documentation:

sudo apt install perl

After installation completes, verify the full package is now installed:

dpkg -l perl | grep -E "^ii"
ii  perl           5.40.1-6build1        amd64        Larry Wall's Practical Extraction and Report Language

Install Additional Perl Modules

Ubuntu provides many pre-packaged Perl modules through APT. The following packages extend Perl’s functionality for common tasks:

  • perl-doc: Official Perl documentation, including reference manuals and tutorials accessible via perldoc.
  • libperl-dev: Development files and libraries for compiling Perl modules and XS extensions.
  • libdbd-mysql-perl: Database driver for connecting Perl applications to MySQL and MariaDB databases.
  • libdatetime-perl: Date and time manipulation modules with time zone support for scheduling and timestamps.
  • libjson-perl: JSON encoding and decoding for REST APIs and web applications.
  • libxml-simple-perl: Simple API for parsing and manipulating XML configuration files and data.
  • libtest-simple-perl: Framework for writing and running Perl unit tests.

To install Perl with commonly used modules, run the following command:

sudo apt install perl libdatetime-perl libjson-perl perl-doc

Search for Available Perl Modules

To discover additional Perl modules in Ubuntu’s repositories, use the apt search command. The following example filters results to show library packages:

apt search perl | grep lib

For modules related to specific functionality, filter the results further. For example, to find MySQL-related Perl packages:

apt search perl | grep -i mysql

Once you identify a package, install it with APT:

sudo apt install libdbd-mysql-perl

For modules not available in Ubuntu’s repositories, you can install them directly from CPAN using the cpan command included with the full Perl package. However, APT-managed modules are generally preferred for better integration with system updates.

Method 2: Install Perl via Source Compilation

Compiling Perl from source provides access to the latest stable release and allows customization of compilation options. This method is particularly useful when you need a specific version, want to enable experimental features, or require optimizations not available in the distribution package.

Install Build Dependencies

First, install the essential development tools required for compilation. The build-essential package includes the GCC compiler and make utility, while curl and wget handle downloading files:

sudo apt install build-essential wget curl -y

If you need more information about setting up the GCC compiler toolchain, see our guide on installing GCC on Ubuntu.

Download Latest Perl Source

The following command automatically fetches the latest stable Perl version from the Perl GitHub repository and downloads the source archive. Perl uses a versioning scheme where even-numbered minor versions (5.40, 5.42) are stable releases, while odd-numbered versions (5.41, 5.43) are development releases:

PERL_VERSION=$(curl -s https://api.github.com/repos/Perl/perl5/tags | grep -oP '"name": "v\K5\.[0-9]+\.[0-9]+' | awk -F. '$2 % 2 == 0' | head -1)
echo "Downloading Perl $PERL_VERSION..."
wget https://www.cpan.org/src/5.0/perl-$PERL_VERSION.tar.gz

This command pipeline performs the following operations:

  • Queries the GitHub API for all Perl version tags.
  • Extracts version numbers matching the pattern 5.X.Y.
  • Filters for stable releases (even-numbered minor versions).
  • Downloads the corresponding source archive from CPAN.

If you prefer to download a specific version manually, visit the Perl download page and replace $PERL_VERSION with your desired version number (e.g., 5.42.0).

Extract and Configure

After the download completes, extract the source archive and navigate to the extracted directory:

tar -xzf perl-$PERL_VERSION.tar.gz
cd perl-$PERL_VERSION

Next, run the configuration script to prepare the build. The -des flags accept default options silently without interactive prompts, and -Dprefix sets the installation directory:

./Configure -des -Dprefix=/usr/local

Configuration typically takes a few minutes and outputs numerous checks as it detects your system’s capabilities.

The -Dprefix=/usr/local option (capital D) installs Perl to /usr/local/bin/perl, keeping it separate from Ubuntu’s system Perl at /usr/bin/perl. This allows both versions to coexist without conflicts.

Compile and Install

Compile the source code using make. The compilation duration depends on your system’s processing power and typically takes 10-30 minutes:

make

Optionally, run the test suite to verify the build completed correctly. While this step adds significant time, it ensures all Perl features work properly on your system:

make test

Finally, install the compiled Perl to the prefix directory:

sudo make install

Verify Source-Compiled Installation

After installation completes, verify that the source-compiled Perl is accessible. Since /usr/local/bin typically takes precedence in PATH, the new version should be the default:

/usr/local/bin/perl -v

Expected output confirming the installation:

This is perl 5, version 42, subversion 0 (v5.42.0) built for x86_64-linux

Copyright 1987-2024, Larry Wall

To verify which Perl binary your shell uses by default:

which perl
/usr/local/bin/perl

If the output shows /usr/bin/perl instead, your PATH may not include /usr/local/bin before /usr/bin. In most Ubuntu configurations, this is not an issue.

Update Script for Source-Compiled Perl

Maintaining a source-compiled Perl installation requires periodic updates. The following script automates the update process by checking for new stable releases and recompiling when a newer version is available. Save it as /opt/perl-build/update-perl.sh:

#!/bin/bash
set -e

BUILD_DIR="/opt/perl-build"
INSTALL_PREFIX="/usr/local"

# Check for required tools
for cmd in curl wget make gcc; do
    if ! command -v $cmd &> /dev/null; then
        echo "Error: $cmd is required but not installed."
        echo "Run: sudo apt install build-essential wget curl"
        exit 1
    fi
done

# Get current installed version
CURRENT_VERSION=$($INSTALL_PREFIX/bin/perl -v 2>/dev/null | grep -oP 'v\K[0-9]+\.[0-9]+\.[0-9]+' | head -1 || echo "none")

# Fetch latest stable version (even minor versions are stable)
LATEST_VERSION=$(curl -s https://api.github.com/repos/Perl/perl5/tags | grep -oP '"name": "v\K5\.[0-9]+\.[0-9]+' | awk -F. '$2 % 2 == 0' | head -1)

if [ -z "$LATEST_VERSION" ]; then
    echo "Error: Could not fetch latest version from GitHub API"
    echo "Check your internet connection or try again later."
    exit 1
fi

echo "Current version: $CURRENT_VERSION"
echo "Latest version:  $LATEST_VERSION"

if [ "$CURRENT_VERSION" = "$LATEST_VERSION" ]; then
    echo "Already up to date."
    exit 0
fi

echo "Updating from $CURRENT_VERSION to $LATEST_VERSION..."

mkdir -p "$BUILD_DIR"
cd "$BUILD_DIR"

# Clean previous builds
rm -rf perl-*/

# Download and extract
wget -q "https://www.cpan.org/src/5.0/perl-$LATEST_VERSION.tar.gz"
tar -xzf "perl-$LATEST_VERSION.tar.gz"
rm "perl-$LATEST_VERSION.tar.gz"

cd "perl-$LATEST_VERSION"
./Configure -des -Dprefix="$INSTALL_PREFIX"
make
make test
sudo make install

# Verify
NEW_VERSION=$($INSTALL_PREFIX/bin/perl -v | grep -oP 'v\K[0-9]+\.[0-9]+\.[0-9]+' | head -1)
echo "Successfully updated to Perl $NEW_VERSION"

Create the build directory and make the script executable:

sudo mkdir -p /opt/perl-build
sudo tee /opt/perl-build/update-perl.sh > /dev/null << 'SCRIPT'
# Paste the script content above
SCRIPT
sudo chmod +x /opt/perl-build/update-perl.sh

Run the update script manually rather than via cron. Compilation can fail due to missing dependencies, network issues, or API rate limits. Manual execution allows you to monitor output and address problems immediately.

Create a Test Perl Script

After installing Perl, verify your installation works correctly by creating a simple test script. This confirms that the interpreter runs properly and can execute Perl code:

nano hello.pl

Add the following Perl code to the file:

#!/usr/bin/env perl
use strict;
use warnings;

print "Hello, world!\n";

Save the file with Ctrl+O, then exit with Ctrl+X. Next, make the script executable and run it:

chmod +x hello.pl
./hello.pl

Expected output:

Hello, world!

The shebang #!/usr/bin/env perl is more portable than #!/usr/bin/perl because it finds whichever Perl is first in your PATH. This approach works correctly whether you use the system Perl or a source-compiled version in /usr/local/bin.

Troubleshoot Common Perl Issues

Module Not Found Errors

If you receive "Can't locate [module].pm in @INC" errors when running Perl scripts, the required module is not installed. First, identify the exact module name from the error message:

Can't locate DateTime.pm in @INC (you may need to install the DateTime module)

Search for the module in Ubuntu's repositories:

apt search perl | grep -i datetime

Then install the corresponding package:

sudo apt install libdatetime-perl

Wrong Perl Version Running

If scripts use an unexpected Perl version, check which binary is being executed:

which perl
perl -v

If the output shows /usr/bin/perl when you expect /usr/local/bin/perl, either specify the full path in your shebang line or ensure /usr/local/bin appears before /usr/bin in your PATH:

export PATH="/usr/local/bin:$PATH"

To make this change permanent, add the export command to your ~/.bashrc file.

Permission Denied When Running Scripts

If you receive "Permission denied" when running a Perl script, the file lacks execute permissions:

chmod +x script.pl

Alternatively, invoke Perl directly on the script file:

perl script.pl

Remove Perl

If you need to remove Perl, follow the steps corresponding to your installation method.

Remove APT-Installed Perl

To remove the full Perl package while keeping the essential base package that system tools depend on:

sudo apt remove perl
sudo apt autoremove

After running apt remove perl, a minimal Perl interpreter remains at /usr/bin/perl via the perl-base package. This is expected behavior because many system tools depend on it. The perl-base package is marked as "Essential" and cannot be removed without breaking your system.

To also remove any additional Perl modules you installed:

sudo apt remove perl perl-doc libdatetime-perl libjson-perl
sudo apt autoremove

Remove Source-Compiled Perl

Warning: The following commands permanently delete the source-compiled Perl installation, including all CPAN modules installed to /usr/local/lib/perl5. If you have custom modules or configurations, back them up before proceeding.

Remove the source-compiled binaries and libraries:

sudo rm -rf /usr/local/bin/perl /usr/local/bin/perl5* /usr/local/bin/cpan
sudo rm -rf /usr/local/lib/perl5
sudo rm -rf /usr/local/share/perl5
sudo rm -rf /usr/local/share/man/man1/perl*
sudo rm -rf /usr/local/share/man/man3/perl*

Optionally, remove the build directory used for compilation and updates:

sudo rm -rf /opt/perl-build

Verify removal by checking which Perl is now in your PATH:

which perl
/usr/bin/perl

The output should now show the system Perl at /usr/bin/perl rather than the source-compiled version.

Conclusion

With Perl installed on Ubuntu, you can leverage its powerful text processing capabilities and extensive CPAN module ecosystem for system administration, web development, and automation tasks. The APT method provides a stable installation with automatic security updates, while source compilation offers access to the latest features and performance improvements. Both approaches integrate well with Ubuntu's system tools, and the troubleshooting section covers common issues you may encounter during development.

Leave a Comment