Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
Что нового в Perl?
   5.10 — 5.16
      Рикардо Синес
    (Ricardo Signes, rjbs)
Perl 5
 Что нового?
Perl 5.10
Для тех, кто не совсем безумен
Perl 5.12
Для использования каждый день
Perl 5.14
  Для прагматиков
Perl 5.16
Для настоящих программистов
Лексическая семантика!
use feature ‘say’;
say “Это тест!”;

{
    no feature ‘say’;
    say “Это ошибка!”;
}
use 5.16.0;
say “Это тест!”;

{
    no feature ‘say’;
    say “Это ошибка!”;
}
#!/usr/bin/perl
use strict;
use warnings;
use 5.16.0; # use feature ‘:5.16’;

my $x = Reticulator->new;
$x->reticulate( @splines );
#!/usr/bin/perl
use strict;
use warnings;
            # no feature;

my $x = Reticulator->new;
$x->reticulate( @splines );
#!/usr/bin/perl
use strict;
use warnings;
            # use feature ‘:default’;

my $x = Reticulator->new;
$x->reticulate( @splines );
array_base: $[
Классные новые фичи!
Лучше сообщения
     об ошибках

$str = “Привет, $name. Последний
визит был $last. Сейчас $time.”;




                              perldiag
Лучше сообщения
       об ошибках

 $str = “Привет, $name. Последний
 визит был $last. Сейчас $time.”;

Use of uninitialized value in
concatenation (.) or string at hello.plx line 9.

                                            perldiag
Лучше сообщения
       об ошибках

 $str = “Привет, $name. Последний
 визит был $last. Сейчас $time.”;

Use of uninitialized value $time in
concatenation (.) or string at hello.plx line 9.

                                            perldiag
state-переменные

my $LINES_READ = 0;
sub read_line {
  $LINES_READ++;
  ...
}

                      perlsub
state-переменные
{
    my $LINES_READ = 0;
    sub read_line {
      $LINES_READ++;
       ...
    }
}
                          perlsub
state-переменные
sub read_line {
  state $LINES_READ = 0;
  $LINES_READ++;
  ...
}


                           perlsub
Истина и определённость




                    perlop
Истина и определённость
  sub record_sale {




                      perlop
Истина и определённость
  sub record_sale {
    my ($product, $amount) = @_;




                               perlop
Истина и определённость
  sub record_sale {
    my ($product, $amount) = @_;
    my $price = $amount




                               perlop
Истина и определённость
  sub record_sale {
    my ($product, $amount) = @_;
    my $price = $amount
               || $product->price;



                                 perlop
Истина и определённость
  sub record_sale {
    my ($product, $amount) = @_;
    my $price = $amount
               || $product->price;

      ...
  }
                                 perlop
Истина и определённость
  sub record_sale {
    my ($product, $amount) = @_;
    my $price = $amount
               || $product->price;

      ...
  }
                                 perlop
Истина и определённость
  sub record_sale {
    my ($product, $amount) = @_;
    my $price = defined $amount
               ? $amount
               : $product->price;
    ...
  }
                                perlop
Истина и определённость
  sub record_sale {
    my ($product, $amount) = @_;
    my $price = $amount
               || $product->price;

      ...
  }
                                 perlop
Истина и определённость
  sub record_sale {
    my ($product, $amount) = @_;
    my $price = $amount
               // $product->price;

      ...
  }
                                 perlop
Новый оператор ИЛИ
sub record_sale {
  my ($product, $amount) = @_;

    $amount //= $product->price;

    ...
}
                                   perlop
say $what


• новая встроенная функция say
• делает тоже самое, что и print
• только добавляет n в конце строки

                                       perlfunc
say $what




            perlfunc
say $what
print “Привет, мир!n”;




                          perlfunc
say $what
print “Привет, мир!n”;


print “$messagen”;




                          perlfunc
say $what
print “Привет, мир!n”;


print “$messagen”;


print “$_n” for @lines;

                           perlfunc
say $what
print “Привет, мир!n”;
say “Привет, мир!”;
print “$messagen”;


print “$_n” for @lines;

                           perlfunc
say $what
print “Привет, мир!n”;
say “Привет, мир!”;
print “$messagen”;
say $message;
print “$_n” for @lines;

                           perlfunc
say $what
print “Привет, мир!n”;
say “Привет, мир!”;
print “$messagen”;
say $message;
print “$_n” for @lines;
say for @lines;
                           perlfunc
Что нового в Perl? 5.10 — 5.16
$ perl -e ‘print “Foon”’
$ perl -e ‘print “Foon”’

$ perl -E ‘say “Foo”’
Рекурсия!

sub fact {
  my ($x) = @_; # must be +int
  return $x if $x == 1;
  return $x * fact($x - 1);
}
Рекурсия!

sub fact {
  my ($x) = @_; # must be +int
  return $x if $x == 1;
  return $x * fact($x - 1);
}
Рекурсия!

my $fact = sub {
   my ($x) = @_; # must be +int
   return $x if $x == 1;
   return $x * $fact->($x - 1);
};
Рекурсия!

my $fact = sub {
   my ($x) = @_; # must be +int
   return $x if $x == 1;
   return $x * $fact->($x - 1);
};
Рекурсия!

my $fact; $fact = sub {
   my ($x) = @_; # must be +int
   return $x if $x == 1;
   return $x * $fact->($x - 1);
};
Рекурсия!

my $fact; $fact = sub {
   my ($x) = @_; # must be +int
   return $x if $x == 1;
   return $x * $fact->($x - 1);
};
Рекурсия!
use Scalar::Util qw(weaken);
my $fact = do {
   my $f1; my $f2 = $f1 = sub {
      my ($x) = @_;
      return $x if $x == 1;
      return $x * $f1->($x - 1);
   };
   weaken($f1);
   $f1;
};
Рекурсия!
use 5.16.0; # current sub

my $fact = sub {
   my ($x) = @_; # must be +int
   return $x if $x == 1;
   return $x * __SUB__->($x - 1);
};
Дескрипторы файлов!
autodie

open my $fh, ‘<‘, $filename;
while (<$fh>) {
   ...
}
close $fh;
                              autodie
autodie
open my $fh, ‘<‘, $filename
  or die “couldn’t open $filename: $!”;
while (<$fh>) {
   ...
}
close $fh
  or die “couldn’t close $filename: $!”;
                                  autodie
autodie

use autodie;
open my $fh, ‘<‘, $filename;
while (<$fh>) {
   ...
}
close $fh;
                              autodie
autodie
use autodie;
open my $fh, ‘<‘, $filename;
while (<$fh>) {
  no autodie;
  rmdir or warn “couldn’t remove $_: $!”;
}
close $fh;
                                  autodie
autodie
use autodie;
sub foo {
   my $filename = shift;
   open my $fh, ‘<‘, $filename;
   while (<$fh>) {
      ...
   }
} # неявный вызов close БЕЗ autodie
                                autodie
IO::File
sub stream_to_fh {
  my ($self, $fh) = @_;
  fileno $fh
    or die “can’t stream to closed fh”;
  while (my $hunk = $self->next_hunk) {
    print {$fh} $hunk;
  }
  close $fh or die “error closing: $!”;
}
                               perlopentut
IO::File
sub stream_to_fh {
  my ($self, $fh) = @_;
  $fh->fileno
    or die “can’t stream to closed fh”;
  while (my $hunk = $self->next_hunk) {
    $fh->print($hunk);
  }
  $fh->close or die “error closing: $!”;
}
                               perlopentut
IO::File

sub stream_to_fh {
  ...
     $fh->print($hunk);
  ...
  $fh->close or die “error closing: $!”;
}
open my $target, ‘>’, ‘/dev/null’
 or die “can’t open bit bucket:$!”;
stream_to_fh($target);
                                      perlopentut
IO::File
use IO::File;
sub stream_to_fh {
  ...
     $fh->print($hunk);
  ...
  $fh->close or die “error closing: $!”;
}
open my $target, ‘>’, ‘/dev/null’
 or die “can’t open bit bucket:$!”;
stream_to_fh($target);
                                      perlopentut
IO::File
use 5.14.0;
sub stream_to_fh {
  ...
     $fh->print($hunk);
  ...
  $fh->close or die “error closing: $!”;
}
open my $target, ‘>’, ‘/dev/null’
 or die “can’t open bit bucket:$!”;
stream_to_fh($target);
                                      perlopentut
IO::File
use 5.14.0; use autodie;
sub stream_to_fh {
  ...
     $fh->print($hunk);
  ...
  $fh->close or die “error closing: $!”;
}
open my $target, ‘>’, ‘/dev/null’
 or die “can’t open bit bucket:$!”;
stream_to_fh($target);
                                      perlopentut
package-блоки
package Library::Awesome;
our $VERSION = 1.234;

sub foo { ... }

1;
                            perlfunc
package-блоки
use 5.12.0;

package Library::Awesome1.234;
sub foo { ... }

1;
                             perlfunc
package-блоки
use 5.12.0;

package Library::Awesome1.234-alpha;
sub foo { ... }

1;
                               perlfunc
package-блоки
use 5.12.0;

package Library::Awesome1.234 {
   sub foo { ... }

}
                              perlfunc
Перегрузка операций

• перегрузка -X
• перегрузка qr
• "no overloading"
• предупреждения неизвестных
  перегрузок операций

                               perldoc
Другие новые фичи!
«Умное» сравнение
      smrt match
«Умное» сравнение


if ($x ~~ $y) {
    ...
}
«Умное» сравнение




                perldoc
«Умное» сравнение

• если $x и $y неизвестны, то существует
  23 возможные вариации
• и некоторые из них — рекурсивные
• нет, вы не будет помнить их все
• ... и они не интуитивные
                                     perldoc
«Умное» сравнение

• если $x и $y неизвестны, то существует
  23 возможные вариации
• и некоторые из них — рекурсивные
• нет, вы не будет помнить их все
• ... и они не интуитивные
                                     perldoc
«Умное» сравнение

• если $x и $y неизвестны, то существует
  23 возможные вариации
• и некоторые из них — рекурсивные
• нет, вы не будет помнить их все
• ... и они не интуитивные
                                     perldoc
«Умное» сравнение

• если $x и $y неизвестны, то существует
  23 возможные вариации
• и некоторые из них — рекурсивные
• нет, вы не будет помнить их все
• ... и они не интуитивные
                                     perldoc
Сравнение
Сравнение
if ($x ~~ $y)               { ... }
if ($str ~~ %hash)          { ... }
if ($str ~~ @arr)           { ... }
if ($str ~~ [ %h, ... ])    { ... }
if (%hash ~~ %h)            { ... }
if (%hash ~~ @arr)          { ... }
if (%hash ~~ [ %h, ... ])   { ... }
Сравнение
if ($x ~~ $y)               { ... }
if ($str ~~ %hash)          { ... }
if ($str ~~ @arr)           { ... }
if ($str ~~ [ %h, ... ])    { ... }
if (%hash ~~ %h)            { ... }
if (%hash ~~ @arr)          { ... }
if (%hash ~~ [ %h, ... ])   { ... }
Сравнение
if ($x ~~ $y)               { ... }
if ($str ~~ %hash)          { ... }
if ($str ~~ @arr)           { ... }
if ($str ~~ [ %h, ... ])    { ... }
if (%hash ~~ %h)            { ... }
if (%hash ~~ @arr)          { ... }
if (%hash ~~ [ %h, ... ])   { ... }
Сравнение
if ($x ~~ $y)               { ... }
if ($str ~~ %hash)          { ... }
if ($str ~~ @arr)           { ... }
if ($str ~~ [ %h, ... ])    { ... }
if (%hash ~~ %h)            { ... }
if (%hash ~~ @arr)          { ... }
if (%hash ~~ [ %h, ... ])   { ... }
Сравнение
if ($x ~~ $y)               { ... }
if ($str ~~ %hash)          { ... }
if ($str ~~ @arr)           { ... }
if ($str ~~ [ %h, ... ])    { ... }
if (%hash ~~ %h)            { ... }
if (%hash ~~ @arr)          { ... }
if (%hash ~~ [ %h, ... ])   { ... }
Сравнение
if ($x ~~ $y)               { ... }
if ($str ~~ %hash)          { ... }
if ($str ~~ @arr)           { ... }
if ($str ~~ [ %h, ... ])    { ... }
if (%hash ~~ %h)            { ... }
if (%hash ~~ @arr)          { ... }
if (%hash ~~ [ %h, ... ])   { ... }
Сравнение
if ($x ~~ $y)               { ... }
if ($str ~~ %hash)          { ... }
if ($str ~~ @arr)           { ... }
if ($str ~~ [ %h, ... ])    { ... }
if (%hash ~~ %h)            { ... }
if (%hash ~~ @arr)          { ... }
if (%hash ~~ [ %h, ... ])   { ... }
given ($x) {
   when ($y) {
      ...
   }
   when ($z) {
      ...
   }
}
given ($x) {
   when ($y) {
      try { ... }
      catch {
         warn “error: $_”;
         return undef;
       }
   }
}
each @array
each @array


while (my ($i, $v) = each @array) {
  say “$i: $v”;
}
push $aref, @etc;
Сейчас с меньшим
количеством багов!
Проблема 2038 года
       y2038
Что нового в Perl? 5.10 — 5.16
~$ perl5.10.0 -E ‘say scalar localtime 2**31-1’
Mon Jan 18 22:14:07 2038

~$ perl5.10.0 -E ‘say scalar localtime 2**31’
Fri Dec 13 15:45:52 1901
~$ perl5.10.0 -E ‘say scalar localtime 2**31-1’
Mon Jan 18 22:14:07 2038

~$ perl5.10.0 -E ‘say scalar localtime 2**31’
Fri Dec 13 15:45:52 1901
~$ perl5.10.0 -E ‘say scalar localtime 2**31-1’
Mon Jan 18 22:14:07 2038

~$ perl5.10.0 -E ‘say scalar localtime 2**31’
Fri Dec 13 15:45:52 1901
~$ perl5.10.0 -E ‘say scalar localtime 2**31-1’
Mon Jan 18 22:14:07 2038

~$ perl5.10.0 -E ‘say scalar localtime 2**31’
Fri Dec 13 15:45:52 1901
Что нового в Perl? 5.10 — 5.16
~$ perl5.12.0 -E ‘say scalar localtime 2**31-1’
Mon Jan 18 22:14:07 2038

~$ perl5.12.0 -E ‘say scalar localtime 2**31’
Mon Jan 18 22:14:08 2038
~$ perl5.12.0 -E ‘say scalar localtime 2**31-1’
Mon Jan 18 22:14:07 2038

~$ perl5.12.0 -E ‘say scalar localtime 2**31’
Mon Jan 18 22:14:08 2038
~$ perl5.12.0 -E ‘say scalar localtime 2**31-1’
Mon Jan 18 22:14:07 2038

~$ perl5.12.0 -E ‘say scalar localtime 2**31’
Mon Jan 18 22:14:08 2038
~$ perl5.12.0 -E ‘say scalar localtime 2**31-1’
Mon Jan 18 22:14:07 2038

~$ perl5.12.0 -E ‘say scalar localtime 2**31’
Mon Jan 18 22:14:08 2038
$@


     perlvar
$@




     Try::Tiny
$@

• Ну, на самом деле, вы используете
  Try::Tiny, верно?
• И это тоже делает Try::Tiny более
  надёжным!
• Вы видите, что eval и $@ — полностью
  ужасны

                                      Try::Tiny
$@

• Ну, на самом деле, вы используете
  Try::Tiny, верно?
• И это тоже делает Try::Tiny более
  надёжным!
• Вы видите, что eval и $@ — полностью
  ужасны

                                      Try::Tiny
$@

• Ну, на самом деле, вы используете
  Try::Tiny, верно?
• И это тоже делает Try::Tiny более
  надёжным!
• Вы видите, что eval и $@ — полностью
  ужасны

                                      Try::Tiny
use 5.12.0;
{
   package X;
   sub DESTROY {
       eval { }
   }
}
eval {
   my $x = bless {} => ‘X’;
   die “DEATH!!”;
};
warn “ERROR: $@”;
$ perl5.12.4 test.pl
ERROR:
                              perlfunc
use 5.12.0;
{
   package X;
   sub DESTROY {
       eval { }
   }
}
eval {
   my $x = bless {} => ‘X’;
   die “DEATH!!”;
};
warn “ERROR: $@”;
$ perl5.12.4 test.pl
ERROR:
                              perlfunc
use 5.14.0;
{
   package X;
   sub DESTROY {
       eval { }
   }
}
eval {
   my $x = bless {} => ‘X’;
   die “DEATH!!”;
};
warn “ERROR: $@”;
$ perl5.12.4 test.pl
ERROR:
                              perlfunc
use 5.14.0;
{
   package X;
   sub DESTROY {
       eval { }
   }
}
eval {
   my $x = bless {} => ‘X’;
   die “DEATH!!”;
};
warn “ERROR: $@”;
$ perl5.14.1 test.pl
ERROR: DEATH!!
                              perlfunc
Что нового в Perl? 5.10 — 5.16
perl -le ‘print $^X’
10.0: perl
10.1: perl
12.0: perl
14.0: perl
16.0: /Users/rjbs/perl5/perlbrew/perls/16.0/bin/perl
perl -le ‘print $^X’
10.0: perl
10.1: perl
12.0: perl
14.0: perl
16.0: /Users/rjbs/perl5/perlbrew/perls/16.0/bin/perl
perl -le ‘print $^X’
10.0: perl
10.1: perl
12.0: perl
14.0: perl
16.0: /Users/rjbs/perl5/perlbrew/perls/16.0/bin/perl
perl -le ‘print $^X’
10.0: perl
10.1: perl
12.0: perl
14.0: perl
16.0: /Users/rjbs/perl5/perlbrew/perls/16.0/bin/perl
perl -le ‘print $^X’
10.0: perl
10.1: perl
12.0: perl
14.0: perl
16.0: /Users/rjbs/perl5/perlbrew/perls/16.0/bin/perl
perl -le ‘print $^X’
10.0: perl
10.1: perl
12.0: perl
14.0: perl
16.0: /Users/rjbs/perl5/perlbrew/perls/16.0/bin/perl
Простые строки
Perl — хорош для Unicode




                   perlunicode
Perl 5.16 лучше




                  perlunicode
Perl 5.16 лучше

• поддержка Unicode 6.1
• доступно каждое свойство символа
• X в регулярных выражениях — более
  осмысленно


                                perlunicode
Perl 5.16 лучше

• поддержка Unicode 6.1
• доступно каждое свойство символа
• X в регулярных выражениях — более
  осмысленно


                                perlunicode
Perl 5.16 лучше

• поддержка Unicode 6.1
• доступно каждое свойство символа
• X в регулярных выражениях — более
  осмысленно


                                perlunicode
«Unicode-баг»




                perlunicode
«Unicode-баг»

• строка не всегда рассматриваются
    как Unicode
• это вызывает странные ошибки, для
    поиска которых требуется время
•   use feature ‘unicode_strings’;
•
                                     perlunicode
«Unicode-баг»

• строка не всегда рассматриваются
  как Unicode
• это вызывает странные ошибки, для
  поиска которых требуется время
• use feature ‘unicode_strings’;
•
                                     perlunicode
«Unicode-баг»

• строка не всегда рассматриваются
  как Unicode
• это вызывает странные ошибки, для
  поиска которых требуется время
• use feature ‘unicode_strings’;
• или use 5.12.0
                                     perlunicode
«Unicode-баг»

• строка не всегда рассматриваются
  как Unicode
• это вызывает странные ошибки, для
  поиска которых требуется время
• use feature ‘unicode_strings’;
• или use 5.12.0
                                     perlunicode
Unicode eval

• eval $str
• это октеты или символы?
• что будет, если это включает в себя
  «use utf8»
• или вы работаете под «use utf8»
                                        perldoc
Unicode eval


• evalbytes $str
• unicode_eval

                        perldoc
Мой любимый 5.12-изм?
if (length $input->{new_email}) {
    $user->update_email(...);
}

Use of uninitialized value in length
at - line 3120.

                                    perldiag
Мой любимый 5.12-изм?
if (length $input->{new_email}) {
    $user->update_email(...);
}

Use of uninitialized value in length
at - line 3120.

                                    perldiag
Мой любимый 5.12-изм?
if (length $input->{new_email}) {
    $user->update_email(...);
}

Use of uninitialized value in length
at - line 3120.

                                    perldiag
say “I o{23145} Perl 5.14!”;

I ♥ Perl 5.14!



                                perlre
say “I o{23145} Perl 5.14!”;

I ♥ Perl 5.14!



                                perlre
say “I 23145 Perl 5.14!”;

I ?45 Perl 5.14!




                             perlre
say “I 023145 Perl 5.14!”;

I 145 Perl 5.14!




                              perlre
say “I 23145 Perl 5.14!”;

I ?45 Perl 5.14!




                             perlre
qr{
  (1) (2) (3) (4)     7 10
  (5) (6) (7) (8) (9) 7 10
  (10)                7 10
}x;


                               perlre
qr{
  (1) (2) (3) (4)     o{7} o{10}
  (5) (6) (7) (8) (9) o{7} o{10}
  (10)                g{7} g {10}
}x;


                                      perlre
Unicode 6.1
Unicode 6.1
•   1F309   — мост в ночи




                            charnames
Unicode 6.1
•   1F309   — мост в ночи
•   026CE   — змееносец




                            charnames
Unicode 6.1
•   1F309   — мост в ночи
•   026CE   — змееносец
•   1F486   — массаж головы




                              charnames
Unicode 6.1
•   1F309   — мост в ночи
•   026CE   — змееносец
•   1F486   — массаж головы
•   1F473   — мужик в тюрбане




                                charnames
Unicode 6.1
•   1F309   — мост в ночи
•   026CE   — змееносец
•   1F486   — массаж головы
•   1F473   — мужик в тюрбане
•   1F423   — вылупившийся цыплёнок




                             charnames
Unicode 6.1
•   1F309   — мост в ночи
•   026CE   — змееносец
•   1F486   — массаж головы
•   1F473   — мужик в тюрбане
•   1F423   — вылупившийся цыплёнок
•   1F424   — цыплёнок




                             charnames
Unicode 6.1
•   1F309   — мост в ночи
•   026CE   — змееносец
•   1F486   — массаж головы
•   1F473   — мужик в тюрбане
•   1F423   — вылупившийся цыплёнок
•   1F424   — цыплёнок
•   1F425   — цыплёнок анфас



                             charnames
Unicode 6.1
•   1F309   — мост в ночи
•   026CE   — змееносец
•   1F486   — массаж головы
•   1F473   — мужик в тюрбане
•   1F423   — вылупившийся цыплёнок
•   1F424   — цыплёнок
•   1F425   — цыплёнок анфас
•   1F421   — иглобрюхие


                             charnames
Unicode 6.1
•   1F309   — мост в ночи
•   026CE   — змееносец
•   1F486   — массаж головы
•   1F473   — мужик в тюрбане
•   1F423   — вылупившийся цыплёнок
•   1F424   — цыплёнок
•   1F425   — цыплёнок анфас
•   1F421   — иглобрюхие
•   1F60B   — облизывающийся смайл

                             charnames
Unicode 6.1
•   1F309   — мост в ночи
•   026CE   — змееносец
•   1F486   — массаж головы
•   1F473   — мужик в тюрбане
•   1F423   — вылупившийся цыплёнок
•   1F424   — цыплёнок
•   1F425   — цыплёнок анфас
•   1F421   — иглобрюхие
•   1F60B   — облизывающийся смайл
•   1F4A9   — куча говна
                             charnames
N{...}

use 5.16.0;

say "I N{HEAVY_BLACK_HEART} Queensr"
  . "N{LATIN_SMALL_LETTER_Y_WITH_DIAERESIS}"
  . "che!";


                                        perldiag
Преобразования регистра
         case folding
Case Folding
Case Folding

if ( lc $foo eq lc $bar ) {
    ...
}
Case Folding

if ( fc $foo eq fc $bar ) {
    ...
}
Case Folding
Case Folding
 lc ‘ς‘ ➔ ‘ς‘
 uc ‘ς‘ ➔ ‘Σ‘
 fc ‘ς‘ ➔ ‘σ‘

 lc ‘ß’ ➔ ‘ß’
 uc ‘ß’ ➔ ‘SS’
 fc ‘ß’ ➔ ‘ss’
Case Folding
 lc ‘ς‘ ➔ ‘ς‘
 uc ‘ς‘ ➔ ‘Σ‘
 fc ‘ς‘ ➔ ‘σ‘

 lc ‘ß’ ➔ ‘ß’
 uc ‘ß’ ➔ ‘SS’
 fc ‘ß’ ➔ ‘ss’
Case Folding
 lc ‘ς‘ ➔ ‘ς‘
 uc ‘ς‘ ➔ ‘Σ‘
 fc ‘ς‘ ➔ ‘σ‘

 lc ‘ß’ ➔ ‘ß’
 uc ‘ß’ ➔ ‘SS’
 fc ‘ß’ ➔ ‘ss’
Case Folding
 lc ‘ς‘ ➔ ‘ς‘
 uc ‘ς‘ ➔ ‘Σ‘
 fc ‘ς‘ ➔ ‘σ‘

 lc ‘ß’ ➔ ‘ß’
 uc ‘ß’ ➔ ‘SS’
 fc ‘ß’ ➔ ‘ss’
Case Folding
 lc ‘ς‘ ➔ ‘ς‘
 uc ‘ς‘ ➔ ‘Σ‘
 fc ‘ς‘ ➔ ‘σ‘

 lc ‘ß’ ➔ ‘ß’
 uc ‘ß’ ➔ ‘SS’
 fc ‘ß’ ➔ ‘ss’
Case Folding
 lc ‘ς‘ ➔ ‘ς‘
 uc ‘ς‘ ➔ ‘Σ‘
 fc ‘ς‘ ➔ ‘σ‘

 lc ‘ß’ ➔ ‘ß’
 uc ‘ß’ ➔ ‘SS’
 fc ‘ß’ ➔ ‘ss’
Case Folding
Case Folding

“file under: L$name”

“file under: F$name”
Case Folding

“file under: L$name”

“file under: F$name”
В регулярных
выражениях стали лучше
именнованные
 сохранения
   named captures
Named captures

• поиск совпадений по имени, а не
  позиции
• избавиться от страшных $1
• больше не второй Python или .Net!

                                      perlre
Named captures

• поиск совпадений по имени, а не
  позиции
• избавиться от страшных $1
• больше не второй Python или .Net!

                                      perlre
Named captures

• поиск совпадений по имени, а не
  позиции
• избавиться от страшных $1
• больше не второй Python или .Net!

                                      perlre
Named captures

# псевдокод
section:property = value




                           perlre
Named captures

$line =~ /(w+):(w+) = (w+)/;

$section = $1;
$name = $2;
$value = $3;



                               perlre
Named captures
 $line =~ /
     (?<section> w+):
     (?<name> w+)
     s* = s*
     (?<value> w+)
 /x;

 $section = $+{section};
 $name = $+{name};
 $value = $+{value};       perlre
Новые модификаторы

 my $hostname = get_hostname;
 $hostname =~ s/..*//;




                                perlre
Новые модификаторы

my $hostname = get_hostname =~ s/..*//;




                                     perlre
Новые модификаторы

(my $hostname = get_hostname) =~ s/..*//;




                                     perlre
Новые модификаторы

my $hostname = get_hostname =~ s/..*//r;




                                     perlre
Новые модификаторы

my @short_names =
   map { s/..*//; } @long_names;




                                    perlre
Новые модификаторы

my @short_names =
   map { s/..*//;
         $_ } @long_names;



                             perlre
Новые модификаторы

my @short_names =
   map { my $x = $_;
         $x =~ s/..*//;
         $x } @long_names;


                             perlre
Новые модификаторы

my @short_names =
   map { s/..*//r } @long_names;




                                    perlre
Новые модификаторы


my @short_names =
   map s/..*//r, @long_names;



                                 perlre
Новые модификаторы




                perldoc
Новые модификаторы
                /u   /a   /aa   /d   /l

"൮" =~ /d/     ✓    ☐    ☐     ¿?   ¿?

"ð" =~ /w/     ✓    ☐    ☐     ¿?   ¿?

"ff" =~ /ff/i   ✓    ✓    ☐     ¿?   ¿?

"ff" =~ /pL/i   ✓    ✓    ✓     ¿?   ¿?

                                     perldoc
Новые модификаторы
                /u   /a   /aa   /d   /l

"൮" =~ /d/     ✓    ☐    ☐     ¿?   ¿?

"ð" =~ /w/     ✓    ☐    ☐     ¿?   ¿?

"ff" =~ /ff/i   ✓    ✓    ☐     ¿?   ¿?

"ff" =~ /pL/i   ✓    ✓    ✓     ¿?   ¿?

                                     perldoc
Новые модификаторы
                /u   /a   /aa   /d   /l

"൮" =~ /d/     ✓    ☐    ☐     ¿?   ¿?

"ð" =~ /w/     ✓    ☐    ☐     ¿?   ¿?

"ff" =~ /ff/i   ✓    ✓    ☐     ¿?   ¿?

"ff" =~ /pL/i   ✓    ✓    ✓     ¿?   ¿?

                                     perldoc
Новые модификаторы
                /u   /a   /aa   /d   /l

"൮" =~ /d/     ✓    ☐    ☐     ¿?   ¿?

"ð" =~ /w/     ✓    ☐    ☐     ¿?   ¿?

"ff" =~ /ff/i   ✓    ✓    ☐     ¿?   ¿?

"ff" =~ /pL/i   ✓    ✓    ✓     ¿?   ¿?

                                     perldoc
Новые модификаторы
                /u   /a   /aa   /d   /l

"൮" =~ /d/     ✓    ☐    ☐     ¿?   ¿?

"ð" =~ /w/     ✓    ☐    ☐     ¿?   ¿?

"ff" =~ /ff/i   ✓    ✓    ☐     ¿?   ¿?

"ff" =~ /pL/i   ✓    ✓    ✓     ¿?   ¿?

                                     perldoc
Новые модификаторы
                /u   /a   /aa   /d   /l

"൮" =~ /d/     ✓    ☐    ☐     ¿?   ¿?

"ð" =~ /w/     ✓    ☐    ☐     ¿?   ¿?

"ff" =~ /ff/i   ✓    ✓    ☐     ¿?   ¿?

"ff" =~ /pL/i   ✓    ✓    ✓     ¿?   ¿?

                                     perldoc
Новые модификаторы
# Только ASCII-символы:
die “Забавные неамериканские символы”
   if $str =~ /P{ASCII}/;
$str =~ /...регулярное выражение.../;



                                 perlre
study




        perldoc
study
my $re = qr{...выражение...};
my $str = q{...long complex...};

$str =~ $re; # slow!!
study $str; # does stuff
$str =~ $re; # fast!!
                                   perldoc
study
my $re = qr{...выражение...};
my $str = q{...длинная строка...};

$str =~ $re; # slow!!
study $str; # does stuff
$str =~ $re; # fast!!
                                     perldoc
study
my $re = qr{...выражение...};
my $str = q{...длинная строка...};

$str =~ $re; # медленно!!
study $str; # does stuff
$str =~ $re; # fast!!
                                     perldoc
study
my $re = qr{...выражение...};
my $str = q{...длинная строка...};

$str =~ $re; # медленно!!
study $str; # используем
$str =~ $re; # fast!!
                                     perldoc
study
my $re = qr{...выражение...};
my $str = q{...длинная строка...};

$str =~ $re; # медленно!!
study $str; # используем
$str =~ $re; # быстро!!
                                     perldoc
study
my $re = qr{...выражение...};
my $str = q{...длинная строка...};

$str =~ $re; # медленно, но верно!!
study $str; # используем
$str =~ $re; # кто знает!!
                                     perldoc
study
my $re = qr{...выражение...};
my $str = q{...длинная строка...};

$str =~ $re; # медленно, но верно!!
study $str; # используем
$str =~ $re; # медленно, но верно!!
                                     perldoc
Замена модулей
    Modder Modlib
Недавно появившиеся
 библиотеки в ядре
• JSON
• HTTP::Tiny
• Module::Metadata
• CPAN::Meta
                     perlmodlib
Недавно удалённые
    библиотеки
• Devel::DProf
• Switch
• perl4 ядро
• ...и другие
                 perlmodlib
Удалён
старый функционал
qw()

for my $show qw(Smallville Lost V) {
   $tivo->cancel_pass( $show );
}




                                   perlop
qw()

for my $show (qw(Smallville Lost V)) {
   $tivo->cancel_pass( $show );
}




                                    perlop
$[
$[ — индекс первого
 элемента в массиве

• можно сделать так, чтобы $array[1]
  возвращал первый элемент массива

• разве это не круто?
• это так же круто, как и шрифт Comic Sans

                                       perlvar
$[ — индекс первого
 элемента в массиве

• можно сделать так, чтобы $array[1]
  возвращал первый элемент массива

• разве это не круто?
• это так же круто, как и шрифт Comic Sans

                                       perlvar
$[ — индекс первого
 элемента в массиве

• можно сделать так, чтобы $array[1]
  возвращал первый элемент массива

• разве это не круто?
• это так же круто, как и шрифт Comic Sans

                                       perlvar
$[ — индекс первого
 элемента в массиве

• можно сделать так, чтобы $array[1]
  возвращал первый элемент массива

• разве это не круто?
• это так же круто, как и шрифт Comic Sans

                                       perlvar
$[

$[ = 1;

for (1 .. $#array) {
  ...
}

                       perlvar
$[

for ($[ .. $#array) {
  ...
}


                        perlvar
$[

   Переназначена переменная $[.
Вы идиот или типа того? at -e line 123.




                                          perlvar
$[

  Use of assignment to $[
is deprecatedat -e line 123.




                               perlvar
defined @arr
Вопросы?
Спасибо за внимание!
Оригинал
      «What's New in Perl?
        v5.10 – v5.16»
http://www.slideshare.net/rjbs/whats-new-in-perl-v510-v516

More Related Content

Что нового в Perl? 5.10 — 5.16