Top Banner
Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES [email protected]
82

Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES [email protected].

Apr 03, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 1/82Introduction à Perl

Introduction à la programmation en Perl

There is more than one way to do it

Élise [email protected]

Page 2: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 2/82Introduction à Perl

Plan du cours

1. Introduction à Perl2. Structures de données3. Structures de contrôle4. Entrées-sorties5. Expressions régulières6. Références7. Modules8. Objets

Page 3: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 3/82Introduction à Perl

Plan du cours

1. Introduction à Perl2. Structures de données3. Structures de contrôle4. Entrées-sorties5. Expressions régulières6. Références7. Modules8. Objets

Page 4: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 4/82Introduction à Perl

Introduction à Perl

Perl : Practical Extraction and Report Language

Langage de programmation dérivé de script Shell, crée par Larry Wall en 1986

Langage interprété : compilation/exécution

Aucune limitation sur la taille des données

Gestion de la taille mémoire n’incombe pas au programmeur

Page 5: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 5/82Introduction à Perl

Introduction à Perl

Avantage de Perl :

écriture rapide d’applications puissantes qui peuvent tourner sur plusieurs plate-formes, prototypage rapide

Page 6: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 6/82Introduction à Perl

Introduction à Perl

Instructions se terminant par un point virgule ;

Commentaires précédés de #

Blocs d’instructions entourés de { }

Page 7: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 7/82Introduction à Perl

Introduction à Perl

Extension des fichiers .pl

1ère ligne des fichiers : chemin accès interpréteur (shebang)#! /usr/local/bin/perl

Attention en Perl, données non typées

Page 8: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 8/82Introduction à Perl

Plan du cours

1. Introduction à Perl

2. Structures de donnéesScalaires, tableaux, tableaux associatifs

3. Structures de contrôle4. Entrées-sorties5. Expressions régulières6. Références7. Modules8. Objets

Page 9: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 9/82Introduction à Perl

Structure de données : données scalaires

Chaînes de caractères :

• “ ” variables interpolées : print “$v” : écrit la valeur de v

• ‘ ‘ pas d’interprétation de la valeur des variables : print ‘$v’ : écrit ‘$v’

Types : chaînes de caractères, nombres, références

Page 10: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 10/82Introduction à Perl

Structure de données : données scalaires

Nombres :

• Plusieurs notations possibles : 123, 123.45, 12e10

• Conversion nombre chaîne de caractère automatique : 125 “125”

Références :

• Pointeur sur une structure de données

Page 11: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 11/82Introduction à Perl

Structure de données : données scalaires

Attention, non obligation de déclarer les variables

Déclaration : my $nom_var [= valeur] ;• my $empty; • my $douze = 12; • my $chaine = hello;• my ($a, $b) = (1, 45);

Nom_var : caractères numériques ou alphanumériques• Nom uniquement chiffré : my $123548 = 123548;

Page 12: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 12/82Introduction à Perl

Chaînes de caractères :

• Concaténation : . : $chaine. à tous; hello à tous

• Multiplication de chaîne : x : $c =bon x3; bonbonbon

• Opérateurs affectation : $x.=$y; $z x= bon;

Structure de données : données scalaires / Opérateurs et fonctions

Page 13: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 13/82Introduction à Perl

Structure de données : données scalaires / Opérateurs et fonctions

Chaînes de caractères :• Fonctions :

• length($c) : longueur

• chop($c) : suppression dernier caractère de $c

• chomp($c) : suppression du dernier caractère si fin de ligne

• reverse($c) : renvoie la chaîne inverse

Page 14: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 14/82Introduction à Perl

• Nombres :• Opérateurs classiques : +, -, /, *, % + tronquer le résultat :

int($x/$y)

• Opérateurs affectation : +=, -=, *=, /=, %= : $x *= 4;

• Puissance : ** : $x**4;

• Fonctions : sin($x), cos($x), exp($x), log($x), abs($x), sqrt($s)

Structure de données : données scalaires / Opérateurs et fonctions

Page 15: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 15/82Introduction à Perl

Structure de données : données scalaires

Fonction defined($v) permet de déterminer si les variables sont définies ou non :

• 0 si var non définie (non initialisée, erreur, fin de fichier)

• 1 sinon

Page 16: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 16/82Introduction à Perl

Structure de données : données scalaires

Opérateurs de tests : Valeurs scalaires fausses : 0, ‘0’ ou 0, chaîne vide ‘’ ou ,

undef, Valeurs scalaires vraies : toute autre valeur

• Opérateurs logiques : and, &&, or, ||, not, !• Opérateurs de comparaison :

$x < = > $y retourne un nombre positif si $x > $y, négatif si $x < $y et 0 si $x == $y

Opérateurs Chaînes nombres

Égalité eq ==

Différence ne !=

Infériorité lt <

Supériorité gt >

Inf ou égal le <=

Sup ou égal ge >=

Comparaison cmp < = >

Page 17: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 17/82Introduction à Perl

Plan du cours

1. Introduction à Perl

2. Structures de donnéesScalaires, tableaux, tableaux associatifs

3. Structures de contrôle4. Entrées-sorties5. Expressions régulières6. Références7. Modules8. Objets

Page 18: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 18/82Introduction à Perl

Structure de données : tableaux et listes

En Perl, pas de distinction entre liste et tableau :

Déclaration : my @nom_tab [=(liste de scalaires)] ;• Tableau : my @t;

• Tableau vide : my @t1 = ();

• Tableau affecté à sa déclaration : my @t2 = (3, ‘chaîne’, bonjour $v); ¬ my @t2 = qw(3 chaîne bonjour $v );

3 éléments 4 éléments

Page 19: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 19/82Introduction à Perl

Structure de données : tableaux et listes

Affectation : • Du tableau : @t1 = qw(2 éléments); OU @t1 = (2,

‘éléments’);

• D’un élément : $t2[2] = 4; @t2 vaut (3, ‘chaine’, 4);

Page 20: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 20/82Introduction à Perl

Structure de données : tableaux et listes

Accès à un élément du tableau : $t[indice] avec indice de 0 à n-1$t2[0] renvoie 3, $t2[1] renvoie ‘chaine’ et $t2[2] renvoie 4

Accès au dernier élément :• $t[-1] retourne la valeur du dernier élément de @t

• $t[$#t] retourne la valeur du dernier élément de @t

• scalar(@t) retourne la longueur du tableau @t

Pas d’erreur si accès à une case du tableau non définie $t[1000] = 12;

• de 3 à 12, les valeurs de @t sont undef • et scalar(@t) = 1001

Page 21: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 21/82Introduction à Perl

Structure de données : tableaux et listes

Opérations sur les tableaux :• Aplatissement :

@t = (1, (deux, 36)); @t = (1, deux, 36);

• Intervalles : @t = (1..5, toto, 5..7) @t = (1,2, 3, 4, 5, toto, 5, 6, 7);

• Répétition : @t = (1,2, 3)X3; @t = (1, 2, 3, 1, 2, 3, 1, 2, 3);

Page 22: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 22/82Introduction à Perl

Structure de données : tableaux et listes

Tableaux particuliers :• @ARGV : contient les arguments de la ligne de

commande

• $0 : contient le nom du programme

• @_ : contient les paramètres des fonctions

Page 23: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 23/82Introduction à Perl

Structure de données : tableaux et listes

Affectations de tableaux à partir d’autres tableaux :• @t = @s; • ($t[1], $t[2]) = (2, toto); • ($t[1], $t[2]) = (2, toto, 3); • ($t[1], $t[2]) = (2); • ($t[1], $t[2]) = @s; • ($t[1], $t[2]) = ($t[2], $t[1]) • my @new = @t[2 .. 15];

@t == @s $t[1] == 2 et $t[2] == toto

$t[1] == 2 et $t[2] == toto, 3 inutile $t[1] == 2 et $t[2] == undefined $t[1] == $s[0] et $t[2] == $s[1]

Page 24: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 24/82Introduction à Perl

Structure de données : tableaux et listes

Fonctions sur les tableaux et listes :

• Ajout et suppression d’éléments à Gauche :• unshift(@tab, liste) : ajout de la liste à Gauche

Soit @t = (1, 2, 3, 4); unshift(@t, 5, 6):

@t == (5, 6, 1, 2, 3, 4)

• shift(@tab) : suppression de l’élément à GaucheSoit @t = (1, 2, 3, 4);

$v = shift(@t): @t == (2, 3, 4) et $v == 1

Page 25: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 25/82Introduction à Perl

Structure de données : tableaux et listes

Fonctions sur les tableaux et listes :

• Ajout et suppression d’éléments à Droite• push(@tab, liste) : ajout de la liste à Droite

Soit @t = (1, 2, 3, 4); push(@t, 5, 6):

@t == (1, 2, 3, 4, 5, 6)

• pop(@tab) : suppression de l’élément à DroiteSoit @t = (1, 2, 3, 4);

$v = shift(@t): @t == (1, 2, 3) et $v == 4

Page 26: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 26/82Introduction à Perl

Structure de données : tableaux et listes

Joindre/Découper des éléments d’une liste :

• scalaire = join(séparateur, liste);Soit @t1 = (1, 2, 3, 4);

$v = join (‘:’, @t); $v == 1:2:3:4

• liste = split(/separateur/, chaine) ;@t2 = (/:/, $v);

@t2 == (1, 2, 3, 4)

Trier une liste : liste1 = sort(liste2);

Page 27: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 27/82Introduction à Perl

Structure de données : tableaux et listes

Sélectionner des éléments : liste1 = grep {sélection} (liste2);@t = grep {>2} @t1;

@t == (3, 4)

@s = grep {$_ !=3 and $_ !=4} @t1 @s == (1, 2)

Traiter une liste complète : liste2 = map({expression} liste1)@m = map ({$_*2} @t1);

@m == (2, 4, 6, 8)

Page 28: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 28/82Introduction à Perl

Plan du cours

1. Introduction à Perl

2. Structures de donnéesScalaires, tableaux, tableaux associatifs

3. Structures de contrôle4. Entrées-sorties5. Expressions régulières6. Références7. Modules8. Objets

Page 29: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 29/82Introduction à Perl

Structure de données : tableaux associatifs ou tables de hachage

Association clé unique-valeur : ‘Paul’ => ’01.23.45.67.89’

Déclaration : • my %h;• my %h = ();• my %h = (‘Paul’ => ’01.23.45.67.89’,

‘Virginie => ’01.02.03.04.05’,‘Pierre’ => ‘je ne sais pas encore’);

Page 30: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 30/82Introduction à Perl

Structure de données : tableaux associatifs ou tables de hachage

Accès à un élément : $h{clé}$h{Paul} renvoie ’01.23.45.67.89’

Autovivification : création élément si accès alors que celui est non existant$h{‘Élise’} ajoutera le couple (‘Élise’ => ()) à %h.

Page 31: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 31/82Introduction à Perl

Structure de données : tableaux associatifs ou tables de hachage

Parcours des tables de hachage :• keys : renvoie une liste des clés, ordre quelconqueordre quelconque

keys(%h) revoie ‘Paul’, ‘Pierre’, ‘Virginie’

• values : renvoie la liste des valeurs, ordre quelconqueordre quelconquevalues(%h) renvoie

‘je ne sais pas’, ’01.23.45.67.89’, ’01.02.03.04.05’

Page 32: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 32/82Introduction à Perl

Structure de données : tableaux associatifs ou tables de hachage

Parcours des tables de hachage :

• each : renvoie tous les couples un à un

each(%h) renvoie le couple (‘Paul’, ’01.23.45.67.89’) : 1er appel

each(%h) renvoie le couple (‘Virginie, ’01.02.03.04.05’) : 2ième appel

each(%h) renvoie le couple (‘Pierre, ‘je ne sais pas encore’) : 3ième appel

Page 33: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 33/82Introduction à Perl

Structure de données : tableaux associatifs ou tables de hachage

Fonctions sur les tables de hachage :• exists : renvoie vrai si l’élément existe

exists($h{‘Paul’}) renverra Vraiexists($h{‘toto’}) renverra Faux

• delete : supprime de la liste le couple associé à la clédelete($h{‘Paul’}) supprime le couple

(‘Paul’ => ’01.23.45.67.89’) de %h

Page 34: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 34/82Introduction à Perl

Structure de données : tableaux associatifs ou tables de hachage

Fonctions sur les tables de hachage :• reverse : inverse les clés et les valeurs

reverse(%h) retourne (‘01.23.45.67.89’ => ‘Paul’, ‘01.02.03.04.05’ => ‘Virginie’,

‘je ne sais pas encore’ => ‘Pierre’)

• %h eq 0 : indique si la table de hachage est vide ou non

Page 35: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 35/82Introduction à Perl

Structure de données : tableaux associatifs ou tables de hachage

Tables de hachage et liste :

Soit une liste @liste = (1, 2, 3, 4, 5, 1, 12, 6, 7).my %h = @liste; crée une table de hachage de la forme :

%h : (1 => 2, retiré car une et une seule clé !!! 3 => 4,

5 => 6, 1 => 12, conservé

7 => 0);

Page 36: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 36/82Introduction à Perl

Plan du cours

1. Introduction à Perl2. Structures de données

3. Structures de contrôleStructures, fonctions

4. Entrées-sorties5. Expressions régulières6. Références7. Modules8. Objets

Page 37: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 37/82Introduction à Perl

Structure de contrôle

Instructions de test :

• Une seule instruction conditionnéeinstruction-unique if (condition);

instruction-unique unless (condition);

• Un bloc conditionné limité par des accolades

if (condition) { instructions; }

if (condition) { instructions1; } else {instructions2;}

if (condition1) { instructions1; } elsif (condition2) { instructions2; }

Page 38: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 38/82Introduction à Perl

Structure de contrôle

Boucles :

• Boucle avec nombre itérations connu : forfor (initialisation; condition ; incrément) { instructions; }

for (my $i = 0; $i < 20; $i++) { print $i; };

Page 39: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 39/82Introduction à Perl

Structure de contrôle

Boucles :

• Boucle sans nombre itération connu : while instruction-unique while/until(condition);

while (condition) {instructions; }do { instructions; } while (condition)

my $j = 0; while ($j < 20) {

print $j; $j += 2; }

do {print $j; $j +=2; }

while ($j < 20)

Page 40: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 40/82Introduction à Perl

Structure de contrôle

Boucles sur des listes de valeurs : foreach variable (liste) { instructions;}

foreach my $v (1, 43, ‘toto’) {print $v;

}

foreach my $i (@t, 32, ‘titi’) {instructions;

}

foreach (@t) {print $_;

}

Page 41: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 41/82Introduction à Perl

Structure de contrôle

Saut d’instructions : • next : fin de l’exécution, incrément évalué puis test• last : fin de la boucle• redo :redémarrage du bloc d’instructions sans incrément

my $i = 1;while (1) {

$i++;last if ($i > 20);next if ($i%2 != 0)print $i;

}

Page 42: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 42/82Introduction à Perl

Plan du cours

1. Introduction à Perl2. Structures de données

3. Structures de contrôleStructures, fonctions

4. Entrées-sorties5. Expressions régulières6. Références7. Modules8. Objets

Page 43: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 43/82Introduction à Perl

Fonctions

La déclaration d’arguments au niveau des fonctions n’est pas obligatoire

sub nom_fonction {déclarations de variables;instructions;return scalaire ou liste;

}

Les variables sont locales à la fonction !!!

Page 44: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 44/82Introduction à Perl

Fonctions

Arguments :• @_ : tableau contenant les paramètres d’appel de la

fonction

+ss paramètres : my ($a, $b, $c) = @_;1 paramètre : my ($a) = @_;

• shift : raccourcis pour un paramètre : my $a = shift;

Page 45: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 45/82Introduction à Perl

Fonctions

sub Puissance { sub Puissance ($$) {my ($v, $p) = @_; my ($v, $p) = @_;if ($v != 0) { if ($v != 0) {

return $p**$v; return $p**$v;} else { } else {

return 1; return 1;} }

} }

my $valeur = Puissance(0, 2);my $valeur2 = Puissance(2, 4, 6);

Page 46: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 46/82Introduction à Perl

Plan du cours

1. Introduction à Perl2. Structures de données3. Structures de contrôle

4. Entrées-sorties5. Expressions régulières6. Références7. Modules8. Objets

Page 47: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 47/82Introduction à Perl

Entrées – Sorties / Standard

Entrée standard : STDIN

my $v = < STDIN > affecte à $v la valeur qui est lue sur l’entrée

Séparation des lignes de l’entrée :while ($v = < STDIN >) || while (<STDIN>) {

instructions avec $v; || instructions avec $_;}do {

$v = <STDIN>; #avec $v déclarée avant la boucle do-while} while ($v)

Lorsque la dernière ligne est atteinte, <STDIN> retourne undef et les boucles arrêtent.

Page 48: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 48/82Introduction à Perl

Entrées – Sorties / Standard

Sortie standard : STDOUT

print (ce qu’il faut écrire); : écrit sur la sortie standardprintf (paramètres de format,ce qu’il faut écrire) : écrit sur la sortie

standardavec le bon format

printf (‘ %5d %5d’, $g, $g); donne …..g…..g

Page 49: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 49/82Introduction à Perl

Entrées – Sorties / Fichier

Opérateurs sur les noms de fichier :• -e : chemin d’accès au fichier valide

If (-e “/usr/temp/fichier”) {print ‘le fichier existe’;

}• -r : vérification des droits du fichier

• -w : vérification du droit d’écriture

• -x : vérification du droit d’exécution

• ……

Page 50: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 50/82Introduction à Perl

Entrées – Sorties / Fichier

Ouverture de fichier : open (HANDLE, “mode ouverture et fichier”)• HANDLE : identifiant du fichier après ouverture EN MAJUSCULE

(convention)• Mode ouverture :

open(FIC1, “+<index.txt”) or die (“not open file”) ;if (! open(FIC2, “<index.txt”)) { instructions; }

Caractères Mode ouverture

Aucun Lecture

< Lecture

> Écriture (écrasement)

>> Écriture (ajout)

+> Lecture et écriture (écrasement)

+< Lecture et écriture (ajout)

Page 51: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 51/82Introduction à Perl

Entrées – Sorties / Fichier

Lecture du fichier • Par ligne: $l = <FIC>;• Toutes les lignes d’un coup : @t = <FIC>;

Parcours de toutes les lignes une à une :while (defined ($l = <FIC>)) || ($l = <FIC>) || (<FIC>)){

chomp($l); || chomp($l); || chomp($_);print “ $. : $l ”; || print “ $. : $l”; où $. == numéro de la

ligne lue.}

Page 52: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 52/82Introduction à Perl

Entrées – Sorties / Fichier

Écriture dans un fichier :print(FIC “ce que j’ai à écrire $v”);printf(FIC “format”, $v);

Fermeture d’un fichier :close(FIC);

Page 53: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 53/82Introduction à Perl

Plan du cours

1. Introduction à Perl2. Structures de données3. Structures de contrôle4. Entrées-sorties

5. Expressions régulières6. Références7. Modules8. Objets

Page 54: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 54/82Introduction à Perl

Expressions régulières

Fonctionnalités : • correspondance (matching) : m/motif/• substitution : s/motif/chaîne/

Opérateurs : =~, !~ ( ! $v =~ m/br/)

$v =~ m/sentier/; recherche du motif sentier dans $v, T ou $v =~ s/sentier/voiture/; remplacement du motif sentier par voiture dans $v

Page 55: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 55/82Introduction à Perl

Expressions régulières

Caractères spéciaux précédés de \ pour la correspondance et la recherche :

\ | ( ) [ ]~^ $ * + ? .

If ($v =~ m/to\?to/) {Instructions; }

Page 56: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 56/82Introduction à Perl

Expressions régulières

Ensembles :

• . : caractère quel qu’il soit

$v =~ s/t.t./titi;

• [] : ensemble de caractère à rechercher$v =~ m/t[oai]t[oai]/;$v =~ s/p[1-9a-z]/pu;

• ^ : ensemble complémentaire $v =~ w/^[a-z]/;

Page 57: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 57/82Introduction à Perl

Expressions régulières

Ensembles :• \d : un chiffre

• \D : un non-numérique

• \w : un alphanumérique

• \W un non alpha-numérique

• \s : un espacement

• \S : un non-espacement

$v =~m/ [+-] \d /

Page 58: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 58/82Introduction à Perl

Expressions régulières

Quantificateurs :

$me =~m/meuh{3}/;

Regroupement : ()$me =~m/(meuh){3}/;

Motif Exemple Mots matchés

* 0 ou plus m/a*/ Mot vide, a, aa, aaa

+ 1 ou plus m/a+/ a, aa, aaa

? 0 ou 1 m/a?/ Mot vide ou a

{n} N fois m/a{3}/ aaa

{n , } Au moins n fois m/a{3,}/ aaa, aaaa, aaaaa

{ , n} Au plus n fois m/a{,3}/ Mot vide, a, aa, aaa

{n, m} Entre n et m fois m/a{2,3}/ aa, aaa

Page 59: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 59/82Introduction à Perl

Expressions régulières

Alternatives : |

$nom =~m/(Fred|Marie | Toto) Martin/;

Assertions :• Début de chaîne : ^

$v =~ m/^T/;• Fin de chaîne : $

$v =~ m/ie$/;

Page 60: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 60/82Introduction à Perl

Plan du cours

1. Introduction à Perl2. Structures de données3. Structures de contrôle4. Entrées-sorties5. Expressions régulières

6. Références7. Modules8. Objets

Page 61: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 61/82Introduction à Perl

Références

Les références permettent de créer des structures complexes pointeurs en C

Les références sont des scalaires !! my $ref;

Elles permettent de passer comme argument aux fonctions des tableaux et des tables de hachages.

Sub pointeurs ($$$) { my ($ref_tab, $ref_hash, $scalaire) = @_;$ref_tab->[3] = ‘zut’;foreach my ($cle, $valeur) = each(%$ref_hash) {

print “$cle, $valuer”;}

$scalaire = 4;}

Page 62: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 62/82Introduction à Perl

Références

Les références permettent de créer des structures complexes pointeurs en C

Opérateur sur les scalaires : anti-slash : \my $refv = \$v;

$refv = référence de $v$$refv = valeur de $v $$refv = 12; $v == 12

@ de $v

$refv

43.5

$v

Page 63: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 63/82Introduction à Perl

Références

Opérateur sur les tableaux : anti-slash : \my $reft = \@t; avec @t = (1, 2, 3 45, 65);

$reft = référence de @t@$reft == @t

Accès aux éléments de @$reft :$$reft[2] == $ref[2] == $t[2] == 3

@ de @t

$reft

1 2 3 45 65

@t

Page 64: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 64/82Introduction à Perl

Références

Opérateur sur les tables de hachage : anti-slash : \my $refh = \%h; avec %h = (Paul, 01, Virginie, 02);

$refh = référence de %h%$refh == %h

Accès aux éléments de %$refh :$refh{Paul} == $$refh{Paul} == $h{Paul} == 01

@ de %h

$reft%h

Paul => 01

Virginie => 02

Page 65: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 65/82Introduction à Perl

Références

Opérateur ref($p) : donne le type de la référence

•“SCALAR” : pointeur sur scalaire

•“ARRAY” : pointeur sur tableau

•“HASH” : pointeur sur table de hachage

• FAUX : $p n’est pas un pointeur

If (ref($p) eq “ARRAY” ) {

foreach my $v (@$p) {

print $v;

}

}

Page 66: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 66/82Introduction à Perl

Références

Références anonymes :

my $ref1 = \34;

my @t = (6, [16, 33], [‘el’, 0.3, 4], s) ;

Page 67: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 67/82Introduction à Perl

Références

Page 68: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 68/82Introduction à Perl

Références

Accès au champ de la clé A : $r->[3]->{A} $$r[3]{A} $r->[3]{A}

Accès au champ 2 de la clé P : $r->[3]->{P}->[2] $$r[3]{P}[2]

Page 69: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 69/82Introduction à Perl

Plan du cours

1. Introduction à Perl2. Structures de données3. Structures de contrôle4. Entrées-sorties5. Expressions régulières6. Références

7. Modules8. Objets

Page 70: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 70/82Introduction à Perl

Modules

Perl tire sa puissance de la richesse des modules existants :

CPAN modules à installer + documentation

+ use Module::Nom_Module

ppm modules déjà installés, à installer, installation

Page 71: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 71/82Introduction à Perl

Modules

Écrire son propre module : NomModule.pm# fichier Utils.pm

Package Utils;

Use stritc;

Sub bonjour {

my $prenom = shift;

print “bonjour $prenom”;

}

1;

Page 72: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 72/82Introduction à Perl

Modules

Utiliser un module : use MonModule;

#! /usr/local/bin/perl

Use Utils;

Utils::bonjour(“Paul”);

Page 73: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 73/82Introduction à Perl

Plan du cours

1. Introduction à Perl2. Structures de données3. Structures de contrôle4. Entrées-sorties5. Expressions régulières6. Références7. Modules

8. Objet

Page 74: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 74/82Introduction à Perl

Objets

Voici les trois grands principes d’implémentation des objets en Perl5 :

• Un objet est simplement une référence qui sait à quelle classe elle appartient (voir la commande bless).

• Une classe est un paquetage qui fournit des méthodes pour travailler sur ces références.

•Une méthode est une fonction qui prend comme premier argument une référence à un objet (ou bien un nom de paquetage).

Page 75: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 75/82Introduction à Perl

Objets

1: # --- fichier Vehicule.pm ---

2: package Vehicule;

3: use strict;

4: sub new

5: {

6: my ($class,$nbRoues,$couleur) = @_;

7: my $self = {};

8: bless($self, $class);

9: $self->{NB_ROUES} = $nbRoues;

10: $self->{COULEUR} = $couleur;

11: return $self;

12: }

13: 1;

sub roule

{

my ($this,$vitesse) = @_;

print "Avec $this->{NB_ROUES} roues,

je roule a $vitesse.\n";

}

Page 76: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 76/82Introduction à Perl

Objets

#!/usr/bin/perl -w

use strict;

use Vehicule;

my $v = Vehicule->new( 2, "bleu" ); my $v = new Vehicule(2, "bleu" );

my $v2 = Vehicule->new( 4, "rouge" );

$v2->roule(15);

Avec 2 roues, je roule à 15.

Page 77: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 77/82Introduction à Perl

Perl

Où trouver de l’aide ?

Page 78: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 78/82Introduction à Perl

Perl

• Lancer l’interpréteur avec l’option -w qui affichera différents messages d’avertissement (variables non initialisées,etc.) très informatifs.

• Avec l’option -c permet de tester uniquement la validité du code sans l’exécuter.

•On peut les combiner en -wc, ce qui testera uniquement la validité syntaxique du code sans l’exécuter.

Page 79: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 79/82Introduction à Perl

Perl

•Pour effectuer des tests encore plus stricts, vous pouvez commencer vos scripts use strict, qui apporte un certain nombre de restrictions visant à vous éviter de commettre des erreurs bêtes (notamment les fautes de frappe dans les noms de variables).

•L’option -w peut être remplacée par use warnings. Vous pouvez même ajouter le use diagnostics pour obtenir des messages d’avertissement plus détaillés.

Page 80: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 80/82Introduction à Perl

Perl

•Si vous ne comprenez toujours pas l’erreur, il reste plusieurs solutions : d’abord, consulter les FAQ initialement maintenues par Tom Christiansen. À partir de la version 5.004_04 de Perl , ces FAQ sont distribuées avec Perl . La commande perldoc perlfaq vous donnera l’index de ces FAQ.

•Une traduction en français de cette FAQ (ainsi que d’autres documentations Perl ) est aussi disponible à l’URL http://perl.enstimac.fr/.

Page 81: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 81/82Introduction à Perl

Perl

•Le réseau CPAN, a été mis en place dans le but de centraliser tous les documents et fichiers relatifs à Perl . Le site principal est ftp.funet.fi et il existe plusieurs miroirs en France dont :

• ftp://ftp.jussieu.fr/pub/Perl/CPAN/,

• ftp://ftp.lip6.fr/pub/perl/CPAN/,

• http://perl.enstimac.fr/CPAN/.

•Il faut noter enfin l’existence de deux sites WWW : http://www.perl.com/ (site géré par les éditions O’Reilly) qui est une source d’informations très précieuse, ainsi que http://www.perl.org/ qui est maintenu par un groupe d’utilisateurs.

Page 82: Page 1/82 Introduction à Perl Introduction à la programmation en Perl There is more than one way to do it Élise VAREILLES vareille@enstimac.fr.

Page 82/82Introduction à Perl

Introduction à la programmation en Perl

There is more than one way to do it

Élise [email protected]