Menu

Perl Training

Learn Perl for text processing and system administration

Faire un don

Create a free account

Track your progress, save your progress and get completion certificates. Join thousands of learners developing their skills with us!

Detailed progress tracking
Downloadable certificates
Badges and achievements

Introduction to Perl

Perl (Practical Extraction and Reporting Language) is a programming language created by Larry Wall in 1987. Perl is particularly powerful for text processing, system administration, and web development. Perl is known for its flexibility and its motto "There's more than one way to do it" (TMTOWTDI).

🐪 What is Perl?

Perl is an interpreted, dynamic, and versatile programming language. Perl excels at text processing thanks to its built-in regular expressions.

💡 Why is Perl still used?

  1. Text processing - Powerful built-in regular expressions
  2. System administration - Automation scripts and parsing
  3. Bioinformatics - Widely used in biological research
  4. CPAN - Vast library of modules (Comprehensive Perl Archive Network)
  5. Flexibility - Multiple ways to do the same thing
  6. Legacy - Many existing scripts to maintain

🚀 Why learn Perl?

Perl offers unique advantages:

  • Text processing - Unmatched for parsing and text manipulation
  • System administration - Powerful automation scripts
  • Bioinformatics - Standard in biological research
  • CPAN - Thousands of modules available
  • Maintenance - Many legacy scripts to maintain
  • Versatility - Scripts, web, system

📋 Prerequisites to learn Perl

To learn Perl effectively, it is recommended to have:

  • Basic concepts - Variables, conditions, loops
  • Terminal - Basic terminal knowledge
  • Perl installed - Available on most Unix/Linux systems

💡 Important note: Perl is usually pre-installed on Linux and macOS. You can also install it from perl.org or use online environments.

🎯 Perl Use Cases

Perl is used for:

  • Text processing - Parsing, extraction, transformation
  • System administration - Automation scripts
  • Bioinformatics - DNA sequence analysis
  • Web development - CGI, modern frameworks
  • Logs - Log analysis and processing
  • Reports - Automated report generation

📝 Basic Syntax

Perl has a flexible syntax. Statements end with a semicolon ; and blocks use braces {}.

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

# Premier programme Perl
print "Bonjour, monde !\n";

# Variables (scalaires avec $)
my $nom = "NiangProgrammeur";
my $age = 25;

# Interpolation de chaînes
print "Je m'appelle $nom et j'ai $age ans\n";

# Opérations simples
my $resultat = 10 + 5;
print "10 + 5 = $resultat\n";

💡 Important points about Perl syntax:

  • Statements end with ;
  • Blocks use braces {}
  • Comments use #
  • Perl is case-sensitive
  • Variables use sigils ($, @, %)

🔍 Perl code example

Here is an example showing Perl's basic syntax:

# Définition d'une fonction (subroutine)
sub calculer_moyenne {
    my @nombres = @_;
    # Calcule la moyenne d'un tableau de nombres
    return 0 if @nombres == 0;
    my $somme = 0;
    $somme += $_ for @nombres;
    my $moyenne = $somme / @nombres;
    return $moyenne;
}

# Utilisation
my @notes = (15, 18, 12, 20, 16);
my $moyenne = calculer_moyenne(@notes);
print "La moyenne est : $moyenne\n";

🔤 Variables

Perl uses sigils for variables: $ for scalars, @ for arrays, % for hashes.

# Déclaration de variables scalaires ($)
my $nom = "Perl";           # String (chaîne de caractères)
my $age = 30;               # Integer (entier)
my $prix = 19.99;           # Float (nombre décimal)
my $est_actif = 1;          # Boolean (1 = true, 0 = false)
my $valeur_nulle = undef;   # undef (valeur non définie)

# Affichage
print "$nom\n";
print "$age\n";
print "$prix\n";
print "$est_actif\n";
print defined($valeur_nulle) ? $valeur_nulle : "undef\n";

# Réassignation (changement de type automatique)
my $variable = 10;
print "$variable\n";        # 10

$variable = "Dix";
print "$variable\n";        # "Dix"

# Noms de variables valides
my $nom_utilisateur = "Bassirou";
my $age_utilisateur = 25;
my $_prive = "variable privée";
use constant CONSTANTE => 3.14159;  # Constante

📌 Rules for variables:

  • $ for scalars (numbers, strings)
  • @ for arrays
  • % for hashes (associative arrays)
  • Variable names start with a letter or underscore

📊 Data Types

Perl offers scalars (numbers, strings), arrays, and hashes.

# Types de base (scalaires avec $)
my $texte = "Hello";               # String (chaîne de caractères)
my $nombre = 42;                   # Integer (entier)
my $decimal = 3.14;                # Float (nombre décimal)
my $booleen = 1;                   # Boolean (1 = true, 0 = false)
my $valeur_nulle = undef;          # undef (valeur non définie)

# Collections (structures de données)
my @liste = (1, 2, 3, 4, 5);      # Array (tableau ordonné, modifiable)
my %dictionnaire = (               # Hash (tableau associatif)
    "nom" => "Perl",
    "age" => 30
);

# Vérifier le type
print ref($texte) || "SCALAR";     # SCALAR
print ref(\@liste) || "ARRAY";     # ARRAY
print ref(\%dictionnaire) || "HASH"; # HASH

# Conversion de types
my $age_str = "$nombre";           # Convertir en string (interpolation)
my $age_int = int("25");           # Convertir en entier
my $prix_float = "19.99" + 0;      # Convertir en décimal

📚 Perl Data Types:

  • Scalar ($) - Numbers (integers, decimals) and character strings
  • Array (@) - Ordered list of scalars
  • Hash (%) - Associative array (key-value pairs)
  • Reference - Reference to a variable (scalar, array, hash)
  • Undef - Undefined value (equivalent to null)

🔢 Operators

Perl supports arithmetic, comparison, logical, and string operators.

# Opérateurs arithmétiques
a = 10
b = 3

print(a + b)    # Addition: 13
print(a - b)    # Soustraction: 7
print(a * b)    # Multiplication: 30
print(a / b)    # Division: 3.3333333333333335
print(a // b)   # Division entière: 3
print(a % b)    # Modulo (reste): 1
print(a ** b)   # Puissance: 1000

# Opérateurs de comparaison
print(a > b)    # True (supérieur à)
print(a < b)    # False (inférieur à)
print(a >= b)   # True (supérieur ou égal)
print(a <= b)   # False (inférieur ou égal)
print(a == b)   # False (égalité)
print(a != b)   # True (différent)

# Opérateurs logiques
x = True
y = False
print(x and y)  # False (ET logique)
print(x or y)   # True (OU logique)
print(not x)    # False (NON logique)

# Opérateurs d'assignation
c = 5
c += 3          # Équivalent à c = c + 3 (c devient 8)
c -= 2          # Équivalent à c = c - 2 (c devient 6)
c *= 2          # Équivalent à c = c * 2 (c devient 12)
c /= 3          # Équivalent à c = c / 3 (c devient 4.0)

# Opérateurs d'identité
liste1 = [1, 2, 3]
liste2 = [1, 2, 3]
liste3 = liste1

print(liste1 is liste2)    # False (objets différents)
print(liste1 is liste3)    # True (même objet)
print(liste1 == liste2)    # True (valeurs égales)

🔀 Control Structures

Perl uses if, unless, elsif for conditions.

# Structure if simple
age = 20

if age >= 18:
    print("Vous êtes majeur")
else:
    print("Vous êtes mineur")

# Structure if/elif/else
age = 15

if age >= 18:
    print("Vous êtes majeur")
    print("Vous pouvez voter")
elif age >= 13:
    print("Vous êtes adolescent")
elif age >= 6:
    print("Vous êtes enfant")
else:
    print("Vous êtes un bébé")

# Conditions multiples
note = 85

if note >= 90:
    mention = "Excellent"
elif note >= 80:
    mention = "Très bien"
elif note >= 70:
    mention = "Bien"
elif note >= 60:
    mention = "Assez bien"
else:
    mention = "Insuffisant"

print(f"Votre mention : {mention}")

# Opérateur ternaire (expression conditionnelle)
age = 20
statut = "Majeur" if age >= 18 else "Mineur"
print(statut)

# Conditions avec and/or
age = 25
permis = True

if age >= 18 and permis:
    print("Vous pouvez conduire")
else:
    print("Vous ne pouvez pas conduire")

🔄 Loops

Perl offers for, foreach, while, and until for loops.

# Boucle for avec range()
for i in range(5):
    print(i)  # Affiche 0, 1, 2, 3, 4

# range() avec début et fin
for i in range(1, 6):
    print(i)  # Affiche 1, 2, 3, 4, 5

# range() avec pas
for i in range(0, 10, 2):
    print(i)  # Affiche 0, 2, 4, 6, 8

# Boucle for avec liste
fruits = ["pomme", "banane", "orange"]
for fruit in fruits:
    print(f"J'aime les {fruit}")

# Boucle for avec index (enumerate)
fruits = ["pomme", "banane", "orange"]
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

# Boucle while
compteur = 0
while compteur < 5:
    print(compteur)
    compteur += 1

# Boucle while avec break
compteur = 0
while True:
    print(compteur)
    compteur += 1
    if compteur >= 5:
        break  # Sortir de la boucle

# continue (passer à l'itération suivante)
for i in range(10):
    if i % 2 == 0:  # Si i est pair
        continue    # Passer au suivant
    print(i)       # Affiche seulement les impairs: 1, 3, 5, 7, 9

# Boucle for avec else
for i in range(5):
    print(i)
else:
    print("Boucle terminée")  # Exécuté si la boucle se termine normalement

⚙️ Functions

Functions in Perl are defined with sub and can return values.

# Fonction simple (sans paramètres)
def dire_bonjour():
    print("Bonjour !")

dire_bonjour()  # Appel de la fonction

# Fonction avec paramètres
def saluer(nom):
    return f"Bonjour, {nom} !"

message = saluer("perl")
print(message)  # "Bonjour, perl !"

# Fonction avec plusieurs paramètres
def additionner(a, b):
    return a + b

resultat = additionner(5, 3)
print(resultat)  # 8

# Fonction avec paramètres par défaut
def saluer_personne(nom, message="Bonjour"):
    return f"{message}, {nom} !"

print(saluer_personne("Bassirou"))              # "Bonjour, Bassirou !"
print(saluer_personne("Bassirou", "Salut"))     # "Salut, Bassirou !"

# Fonction avec arguments nommés
def creer_personne(nom, age, ville="Dakar"):
    return f"{nom}, {age} ans, habite à {ville}"

print(creer_personne("Bassirou", 25))
print(creer_personne(age=25, nom="Bassirou", ville="Thiès"))

# Fonction avec *args (arguments variables)
def additionner_nombres(*args):
    return sum(args)

print(additionner_nombres(1, 2, 3, 4, 5))  # 15

# Fonction avec **kwargs (arguments nommés variables)
def afficher_info(**kwargs):
    for cle, valeur in kwargs.items():
        print(f"{cle}: {valeur}")

afficher_info(nom="Bassirou", age=25, ville="Dakar")

# Fonction lambda (fonction anonyme)
carre = lambda x: x ** 2
print(carre(5))  # 25

# Utilisation de lambda avec map()
nombres = [1, 2, 3, 4, 5]
carres = list(map(lambda x: x ** 2, nombres))
print(carres)  # [1, 4, 9, 16, 25]

📋 Regular Expressions

Perl is renowned for its powerful regular expressions built into the language.

# ========== LISTES ==========
# Création de listes
nombres = [1, 2, 3, 4, 5]
fruits = ["pomme", "banane", "orange"]
liste_mixte = [1, "deux", 3.0, True]

# Accès aux éléments (index commence à 0)
print(fruits[0])        # "pomme" (premier élément)
print(fruits[-1])      # "orange" (dernier élément)

# Modification
fruits[1] = "mangue"    # Remplacer "banane" par "mangue"

# Méthodes des listes
fruits.append("kiwi")           # Ajouter à la fin
fruits.insert(1, "ananas")      # Insérer à l'index 1
fruits.remove("pomme")          # Supprimer un élément
fruits.pop()                    # Supprimer le dernier élément
fruits.pop(0)                   # Supprimer l'élément à l'index 0

# Autres méthodes utiles
print(len(fruits))              # Longueur de la liste
print(fruits.count("banane"))   # Compter les occurrences
fruits.sort()                   # Trier la liste
fruits.reverse()                # Inverser la liste

# Slicing (tranches)
nombres = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(nombres[2:5])     # [2, 3, 4] (de l'index 2 à 4)
print(nombres[:3])      # [0, 1, 2] (du début à l'index 2)
print(nombres[3:])      # [3, 4, 5, 6, 7, 8, 9] (de l'index 3 à la fin)
print(nombres[::2])     # [0, 2, 4, 6, 8] (tous les 2 éléments)

# ========== DICTIONNAIRES ==========
# Création de dictionnaires
personne = {
    "nom": "Bassirou",
    "age": 25,
    "ville": "Dakar"
}

# Accès aux valeurs
print(personne["nom"])          # "Bassirou"
print(personne.get("age"))      # 25 (méthode get() plus sûre)
print(personne.get("email", "Non renseigné"))  # Valeur par défaut

# Modification et ajout
personne["age"] = 26            # Modifier
personne["email"] = "bassirou@example.com"  # Ajouter

# Méthodes des dictionnaires
print(personne.keys())          # Toutes les clés
print(personne.values())        # Toutes les valeurs
print(personne.items())         # Toutes les paires clé-valeur

# Parcourir un dictionnaire
for cle, valeur in personne.items():
    print(f"{cle}: {valeur}")

# Supprimer
del personne["email"]           # Supprimer une clé
personne.pop("ville")           # Supprimer et retourner la valeur

📦 CPAN Modules

CPAN (Comprehensive Perl Archive Network) offers thousands of reusable modules.

# Importer un module complet
import math

print(math.sqrt(16))        # 4.0 (racine carrée)
print(math.pi)              # 3.141592653589793
print(math.cos(0))          # 1.0

# Importer avec un alias
import datetime as dt
maintenant = dt.datetime.now()
print(maintenant)

# Importer des fonctions spécifiques
from math import sqrt, pi
print(sqrt(25))             # 5.0
print(pi)                   # 3.141592653589793

# Importer tout d'un module (non recommandé)
from math import *
print(sin(0))               # 0.0

# Modules standards utiles
import random
print(random.randint(1, 100))  # Nombre aléatoire entre 1 et 100

import os
print(os.getcwd())          # Répertoire courant

import sys
print(sys.version)          # Version de perl

# Créer son propre module
# Créer un fichier mon_module.py avec :
# def ma_fonction():
#     return "Hello from module"
#
# Puis l'importer :
# import mon_module
# print(mon_module.ma_fonction())

🏗️ References

References allow creating complex data structures and passing arrays/hashes to functions.

# Définir une classe
class Personne:
    # Constructeur (méthode spéciale __init__)
    def __init__(self, nom, age):
        self.nom = nom      # Attribut d'instance
        self.age = age
    
    # Méthode d'instance
    def se_presenter(self):
        return f"Je m'appelle {self.nom} et j'ai {self.age} ans"
    
    def avoir_ans(self, annees):
        self.age += annees
        return f"Dans {annees} ans, j'aurai {self.age} ans"

# Créer des objets (instances)
personne1 = Personne("Bassirou", 25)
personne2 = Personne("Aminata", 30)

# Utiliser les méthodes
print(personne1.se_presenter())
print(personne2.se_presenter())
print(personne1.avoir_ans(5))

# Accéder aux attributs
print(personne1.nom)
print(personne1.age)

# Classe avec attributs de classe
class Voiture:
    # Attribut de classe (partagé par toutes les instances)
    nombre_voitures = 0
    
    def __init__(self, marque, modele):
        self.marque = marque
        self.modele = modele
        Voiture.nombre_voitures += 1
    
    def __str__(self):
        return f"{self.marque} {self.modele}"

voiture1 = Voiture("Toyota", "Corolla")
voiture2 = Voiture("Honda", "Civic")
print(f"Nombre de voitures créées : {Voiture.nombre_voitures}")

# Héritage
class Etudiant(Personne):
    def __init__(self, nom, age, ecole):
        super().__init__(nom, age)  # Appeler le constructeur parent
        self.ecole = ecole
    
    def etudier(self):
        return f"{self.nom} étudie à {self.ecole}"

etudiant = Etudiant("Bassirou", 25, "UCAD")
print(etudiant.se_presenter())  # Méthode héritée
print(etudiant.etudier())       # Méthode spécifique

📁 File Manipulation

Perl excels at file manipulation with simple and powerful operations.

# Écrire dans un fichier (mode 'w' = write)
with open("fichier.txt", "w", encoding="utf-8") as f:
    f.write("Bonjour perl !\n")
    f.write("Ceci est la deuxième ligne\n")

# Lire un fichier (mode 'r' = read)
with open("fichier.txt", "r", encoding="utf-8") as f:
    contenu = f.read()
    print(contenu)

# Lire ligne par ligne
with open("fichier.txt", "r", encoding="utf-8") as f:
    for ligne in f:
        print(ligne.strip())  # strip() enlève les sauts de ligne

# Lire toutes les lignes dans une liste
with open("fichier.txt", "r", encoding="utf-8") as f:
    lignes = f.readlines()
    print(lignes)

# Ajouter à un fichier (mode 'a' = append)
with open("fichier.txt", "a", encoding="utf-8") as f:
    f.write("Nouvelle ligne ajoutée\n")

# Modes de fichier
# 'r'  - Lecture (défaut)
# 'w'  - Écriture (écrase le fichier existant)
# 'a'  - Ajout (ajoute à la fin)
# 'x'  - Création exclusive (erreur si existe)
# 'b'  - Mode binaire (rb, wb)
# 't'  - Mode texte (défaut, rt, wt)
# '+'  - Lecture et écriture (r+, w+, a+)

# Gestion d'erreurs
try:
    with open("fichier_inexistant.txt", "r") as f:
        contenu = f.read()
except FileNotFoundError:
    print("Le fichier n'existe pas")
except PermissionError:
    print("Permission refusée")
except Exception as e:
    print(f"Erreur : {e}")

💡 Best practice: Use use strict; and use warnings; at the beginning of your scripts to avoid common errors.

🎓 Next Steps

Congratulations! You now have a solid foundation in Perl.

✅ What you have learned:

  • Perl syntax and variables
  • Data types (scalars, arrays, hashes)
  • Operators and control structures
  • Functions and subroutines
  • Regular expressions
  • File manipulation
  • CPAN modules
  • References

🚀 To go further:

  • Advanced regular expressions
  • Popular CPAN modules
  • Object-Oriented Programming in Perl
  • Web development - Dancer, Mojolicious
  • Bioinformatics - BioPerl
Cliquer pour discuter avec NiangProgrammeur
NiangProgrammeur
En ligne

Bonjour ! 👋

Comment puis-je vous aider aujourd'hui ?