Mot-clef: Perl

Perl – Rechercher une expression et garder plusieurs lignes

octobre 23rd, 2008

Imaginez le texte :

2008-01-02: first entry
2008-02-03: second entry on two lines
    here is the additional line
2008-03-04: third entry
   has
   three
   extra lines
2008-04-05: fourth entry has just one on line again

Question :

Comment faire pour avoir le groupe de lignes qui contient un mot, par exemple « three » ?

Solution :

my @stuff;
while (<IN>) {
    if (/^\s/) { $stuff[-1] .= $_; }
    else { push @stuff, $_;  }
}
print grep { /three/ } @stuff;

Donne :

2008-03-04: third entry
   has
   three
   extra lines

Source

Tags:
Posted in System | 1 Comment »

Perl – Attribut method

octobre 21st, 2008

Les méthodes en Perl, ne tirent pas partie du prototypage :-( , aussi vos méthodes d’objet pourront être confondues avec des fonctions sans prototype.

L’attribut method est bien pratique lorsque vous ne voulez pas que Perl confonde le nom de votre méthode avec une fonction portant le même nom.

Ainsi, vous pouvez créer une méthode print, Perl l’interprétera comme une méthode objet et non comme le fonction built-in print de Perl. Elle sera utilisé lors d’un appel orienté objet.

Exemple :

sub print : method {
   my $self = shift;
   printf("%s print method call\n",__PACKAGE__);
}

Tags:
Posted in System | No Comments »

Perl – La magie du diamant

octobre 17th, 2008

L’opérateur diamant <> est déjà surprenant car il s’occupe indifféremment de lier l’entrée standard ou le contenu des fichiers passés en paramètres.

Plus fort, en redéfinissant @ARGV, vous pouvez lui passer indifféremment un fichier gzippé ou pas.

L’exemple :

@ARGV = map { /\.(gz|Z)$/ ? "gzip -dc $_ |" : $_  } @ARG ;
while(<>) {
 ... A vous de jouer avec $_ = ligne courante ...
}

Tags:
Posted in System | No Comments »

Perl – Le dresseur de signaux

octobre 16th, 2008

« Le dresseur de signaux » vient de : tr.voila.fr

C’est ici, juste une histoire d’indirection de signaux.

L’indirection :

sub signal_handler {
  my $signal=shift;
  printf("signal reçu: %s\n", $signal);
  ... traitement du signal ;-)  ...
  printf("Impossible de dresser le signal: %s\n",$signal);
  return undef;
}

Le code :

$SIG{'INT'} =\&signal_handler;
$SIG{'TERM'}=\&signal_handler;
$SIG{'QUIT'}=\&signal_handler;
$SIG{'USR2'}=\&signal_handler;
$SIG{'HUP'}='IGNORE';

Doc : man kill

Tags:
Posted in System | No Comments »

Perl – Singleton Pattern

octobre 13th, 2008

C’est l’histoire d’une classe d’objet qui ne sait donner qu’une seule instance :-( .
Cette instance sera accessible via le constructeur new.

Le code :

package MonPaquetage;
my $singleton;
BEGIN {
$singleton = {
attribut1 => 'valeur',
attribut2 => 'autre',
};
bless $singleton, "
MonPaquetage";
}

sub new {
my $class = shift;
return $singleton;
}

L’ Appel :

my $obj =
MonPaquetage->new;

Tags: , ,
Posted in System | No Comments »

Page suivante Page précédente