Nouveautés dans perl 5.6.0 (et aussi nouveautés que je n'avais pas remarquées dans les versions précédentes) perlunicode use utf8; \p{ some unicode property } if this property holds \P{ some unicode property } if this property does not hold POSIX (on voudra généralement mettre ce genre de chose entre crochets, ce qui donnera des trucs du genre [[:alpha:]]) /[:alpha:]/ # Un caractère alphabétique /[:alnum:]/ /[:ascii:]/ /[:ascii:]/ /[:cntrl:]/ /[:digit:]/ # \d /[:graph:]/ /[:lower:] /[:print:]/ /[:punct:]/ /[:space:]/ # \s /[:upper:]/ /[:xdigit:]/ /[:word:]/ # \w Négation /[:^alpha:]/ etc. Unicode \p{IsAlpha} \p{IsAlnum} \p{IsASCII} \p{IsCntrl} \p{IsDigit} \p{IsGraph} \p{IsLower} \p{IsPrint} \p{IsPunct} \p{IsSpace} \p{IsUpper} \p{IsXDigit} \p{IsWord} Négations: \P{IsAlpha} etc. Unicode print "Foo bar \N{WHILE SMILING FACE}\n"; Unicode print "\x{263a}"; # Smiley attributes: functions (and variables) may have attributes. for instance, in a threaded program, an object may be locked while running a method on it. Example: sub foo :method :locked { ... } packages may define their own attributes Example: package Felis; my $cat : Nervous; is equivalent to use attributes Felis => \$cat, "Nervous"; File::Glob La fonction glob, et donc les constructions <*.[ch]> ou <{a*,b*}> ne sont plus passées au C-Shell. Il n'est pas nécessaire de préciser use File::Glob sauf si on veut changer les options par défaut, par exemple use File::Glob qw(:globally :nocase); # case insensitive Term::ANSIColor use Term::ANSIColor; print color 'bold blue'; print "This text is bold blue.\n"; print color 'reset'; print "This text is normal.\n"; print colored ("Yellow on magenta.\n", 'yellow on_magenta'); print "This text is normal.\n"; use Term::ANSIColor qw(:constants); print BOLD, BLUE, "This text is in bold blue.\n", RESET; use Term::ANSIColor qw(:constants); $Term::ANSIColor::AUTORESET = 1; print BOLD BLUE "This text is in bold blue.\n"; print "This text is normal.\n"; Débuggeur perl -de 1 Cela lance en fait perl5db.pl perlfilter.pod On peut "filtrer" un source Perl avant qu'il ne soit lu, par exemple par gzip ou bzip2 (pour pouvoir lire de manière transparente des scripts comporessés) ou par cpp. perl -MCPAN -e shell CPAN::FirstTime::init() Binary Les nombres suivants valent tous 10. 10 012 0xA 0b1010 Pour afficher le nombre 10 en hexadécimal, octal, binaire printf "%x", 10; printf "%o", 10; print oct(10); printf "%b", 10; Je rappelle en passant que la commande chr traduit un nombre en caractère ASCII la commande ord traduit un caractère ASCII en nombre. Sort subroutines sub foo ($$) { my($x,$y) = @_; return $x < $y; } my @a = (1,8,6,5,4); my @b = sort foo @a ; # slower than with unnamed subroutines print join(' ', @b); Sort subroutines may be references sub foo ($$) { my($x,$y) = @_; return $x < $y; } my @a = (1,8,6,5,4); my $ref = \&foo; my @b = sort $ref @a ; print join(' ', @b); Files can be automatically closed { open my $fh, "/etc/passwd"; while(<$fh>){ print } } # $fh automatically closed (it is more useful when you _write_ to a file) Pseudo-hashes (perlref) One may replace a hash reference by an array reference. The first element of the array must contain the correspondence between hash keys and array indices. $struct = [{foo => 1, bar => 2}, "FOO", "BAR"]; $struct->{foo}; # same as $struct->[1], i.e. "FOO" $struct->{bar}; # same as $struct->[2], i.e. "BAR" keys %$struct; # will return ("foo", "bar") in some order values %$struct; # will return ("FOO", "BAR") in same some order while (my($k,$v) = each %$struct) { print "$k => $v\n"; } Creation of a pseudo-hash: use fields; $pseudohash = fields::phash(foo => "FOO", bar => "BAR"); etc. foreach On peut mettre la tête de la boucle après son corps (comme pour if) print foreach (0..9); Autre exemple: $_ **= $_ , / {$_} / for 2 .. 42; my dans les boucles foreach my $a (...) {...} my dans les conditionnelles if( my $a = ... ) { ... $a ... } elseif( ... $a ... ) { ... $a ...} else { ... $a ... } Data::Dumper Pour imprimer des variables Perl. use Data::Dumper; $a = { A => { 1 => 'foo', 10 => 'bar' }, B => {2=>0,5=>0} }; print Dumper($a); Il faut que l'argument soit une référence. use Data::Dumper; %a = ( A => { 1 => 'foo', 10 => 'bar' }, B => {2=>0,5=>0} ); print Dumper(\%a); Voir d'autres exemples dans la page de manuel. Benchmark use Benchmark; $x = 3.14; timethese( -5, # Au moins 5 secondes (un nombre positif désigne le nb d'iter) { a => sub { $x * $x }, b => sub { $x ** 2 }, }, ); Env On peut accéder aux variables PATH et consors comme si c'étaient des listes. use Enw qw(@PATH, @LD_LIBRARY_PATH, SHELL); Getopt::Long et Pod::Usage use Pod::Usage; use Getopt::Long; ## Parse options GetOptions("help", "man", "flag1") || pod2usage(2); pod2usage(1) if ($opt_help); pod2usage(-verbose => 2) if ($opt_man); ## Check for too many filenames pod2usage("$0: Too many files given.\n") if (@ARGV > 1); Constantes use constant TRUE => (0==0); use constant FALSE => (0==1); Expressions régulières * Match 0 or more times + Match 1 or more times ? Match 1 or 0 times {n} Match exactly n times {n,} Match at least n times {n,m} Match at least n but not more than m times *? +? ?? {n}? {n,}? {n,m}? : not greedy On peut mettre des expressions régulières précompilées dans des variables. $a = qr{ ... }; if(m/$a/) {...} The `\G' assertion can be used to chain global matches (using `m//g'), as described in the Regexp Quote-Like Operators entry in the perlop manpage. It is also useful when writing `lex'-like scanners, when you have several patterns that you want to match against consequent substrings of your string, see the previous reference. The actual location where `\G' will match can also be influenced by using `pos()' as an lvalue. See the pos entry in the perlfunc manpage. Extended patterns (? ... ) locally case insensitive /(?i:foo)bar/ will match foobar Foobar FOObar but not fooBar /(?-i:foo)bar/i the contrary Look ahead /foo(?=\s)/ matches foo followed by a space, not including the space. /foo(?!\s)/ matches foo not followed by a space Look behind only works with fixed width look-behind /(?<=RE)/ /(? [^()]+ ) # Non-parens without backtracking | (??{ $re }) # Group with matching parens )* \) }x; Independent subexpression (to prevent backtracking) /(?>RE)/ Conditions m/(?(COND)YES|NO)/ m/(?(COND)YES)/ Example: non-parentheses, possibly included in parentheses themselves. m{ (\()? [^()]+ (?(1)\)) }x Mon Jul 31 14:53:40 CEST 2000