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

Preview:

DESCRIPTION

Перевод презентации @rjbs "What's new in Perl? v5.10 — v5.16" http://www.slideshare.net/rjbs/whats-new-in-perl-v510-v516

Citation preview

Что нового в 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/perluse strict;use warnings;use 5.16.0; # use feature ‘:5.16’;

my $x = Reticulator->new;$x->reticulate( @splines );

#!/usr/bin/perluse strict;use warnings; # no feature;

my $x = Reticulator->new;$x->reticulate( @splines );

#!/usr/bin/perluse strict;use warnings; # use feature ‘:default’;

my $x = Reticulator->new;$x->reticulate( @splines );

array_base: $[

Классные новые фичи!

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

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

perldiag

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

perldiag

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

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

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

perldiag

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

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

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

perlfunc

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

• только добавляет \n в конце строки

say $what

perlfunc

perlfunc

print “Привет, мир!\n”;

say $what

perlfunc

print “Привет, мир!\n”;

print “$message\n”;

say $what

perlfunc

print “Привет, мир!\n”;

print “$message\n”;

print “$_\n” for @lines;

say $what

perlfunc

print “Привет, мир!\n”;

say “Привет, мир!”;

print “$message\n”;

print “$_\n” for @lines;

say $what

perlfunc

print “Привет, мир!\n”;

say “Привет, мир!”;

print “$message\n”;

say $message;

print “$_\n” for @lines;

say $what

say $what

perlfunc

print “Привет, мир!\n”;

say “Привет, мир!”;

print “$message\n”;

say $message;

print “$_\n” for @lines;

say for @lines;

$ perl -e ‘print “Foo\n”’

$ perl -e ‘print “Foo\n”’

$ 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

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

IO::File

perlopentut

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: $!”;}

IO::File

perlopentut

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: $!”;}

IO::File

perlopentut

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);

IO::File

perlopentut

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);

IO::File

perlopentut

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);

IO::File

perlopentut

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);

package-блоки

perlfunc

package Library::Awesome;

our $VERSION = 1.234;

sub foo { ... }

1;

package-блоки

perlfunc

use 5.12.0;

package Library::Awesome1.234;

sub foo { ... }

1;

package-блоки

perlfunc

use 5.12.0;

package Library::Awesome1.234-alpha;

sub foo { ... }

1;

package-блоки

perlfunc

use 5.12.0;

package Library::Awesome1.234 {

sub foo { ... }

}

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

perldoc

• перегрузка -X• перегрузка qr

• "no overloading"

• предупреждения неизвестныхперегрузок операций

Другие новые фичи!

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

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

if ($x ~~ $y) {

...

}

perldoc

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

perldoc

• если $x и $y неизвестны, то существует 23 возможные вариации

• и некоторые из них — рекурсивные

• нет, вы не будет помнить их все

• ... и они не интуитивные

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

perldoc

• если $x и $y неизвестны, то существует 23 возможные вариации

• и некоторые из них — рекурсивные

• нет, вы не будет помнить их все

• ... и они не интуитивные

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

perldoc

• если $x и $y неизвестны, то существует 23 возможные вариации

• и некоторые из них — рекурсивные

• нет, вы не будет помнить их все

• ... и они не интуитивные

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

perldoc

• если $x и $y неизвестны, то существует 23 возможные вариации

• и некоторые из них — рекурсивные

• нет, вы не будет помнить их все

• ... и они не интуитивные

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

Сравнение

Сравнение

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

while (my ($i, $v) = each @array) {

say “$i: $v”;

}

each @array

push $aref, @etc;

Сейчас с меньшим количеством багов!

Проблема 2038 годаy2038

~$ 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

~$ 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, верно?

• И это тоже делает Try::Tiny более надёжным!

• Вы видите, что eval и $@ — полностью ужасны

$@

Try::Tiny

• Ну, на самом деле, вы используете Try::Tiny, верно?

• И это тоже делает Try::Tiny более надёжным!

• Вы видите, что eval и $@ — полностью ужасны

$@

Try::Tiny

• Ну, на самом деле, вы используете Try::Tiny, верно?

• И это тоже делает Try::Tiny более надёжным!

• Вы видите, что eval и $@ — полностью ужасны

$@

use 5.12.0;{ package X; sub DESTROY { eval { } }}eval { my $x = bless {} => ‘X’; die “DEATH!!”;};warn “ERROR: $@”;

$ perl5.12.4 test.plERROR:

perlfunc

use 5.12.0;{ package X; sub DESTROY { eval { } }}eval { my $x = bless {} => ‘X’; die “DEATH!!”;};warn “ERROR: $@”;

$ perl5.12.4 test.plERROR:

perlfunc

use 5.14.0;{ package X; sub DESTROY { eval { } }}eval { my $x = bless {} => ‘X’; die “DEATH!!”;};warn “ERROR: $@”;

$ perl5.12.4 test.plERROR:

perlfunc

use 5.14.0;{ package X; sub DESTROY { eval { } }}eval { my $x = bless {} => ‘X’; die “DEATH!!”;};warn “ERROR: $@”;

$ perl5.14.1 test.plERROR: DEATH!!

perlfunc

perl -le ‘print $^X’

10.0: perl10.1: perl12.0: perl14.0: perl16.0: /Users/rjbs/perl5/perlbrew/perls/16.0/bin/perl

perl -le ‘print $^X’

10.0: perl10.1: perl12.0: perl14.0: perl16.0: /Users/rjbs/perl5/perlbrew/perls/16.0/bin/perl

perl -le ‘print $^X’

10.0: perl10.1: perl12.0: perl14.0: perl16.0: /Users/rjbs/perl5/perlbrew/perls/16.0/bin/perl

perl -le ‘print $^X’

10.0: perl10.1: perl12.0: perl14.0: perl16.0: /Users/rjbs/perl5/perlbrew/perls/16.0/bin/perl

perl -le ‘print $^X’

10.0: perl10.1: perl12.0: perl14.0: perl16.0: /Users/rjbs/perl5/perlbrew/perls/16.0/bin/perl

perl -le ‘print $^X’

10.0: perl10.1: perl12.0: perl14.0: perl16.0: /Users/rjbs/perl5/perlbrew/perls/16.0/bin/perl

Простые строки

perlunicode

Perl — хорош для Unicode

perlunicode

Perl 5.16 лучше

perlunicode

• поддержка Unicode 6.1

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

Perl 5.16 лучше

perlunicode

• поддержка Unicode 6.1

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

Perl 5.16 лучше

perlunicode

• поддержка Unicode 6.1

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

Perl 5.16 лучше

perlunicode

«Unicode-баг»

perlunicode

• строка не всегда рассматриваютсякак Unicode

• это вызывает странные ошибки, для поиска которых требуется время

• use feature ‘unicode_strings’;

«Unicode-баг»

perlunicode

• строка не всегда рассматриваютсякак Unicode

• это вызывает странные ошибки, для поиска которых требуется время

• use feature ‘unicode_strings’;

«Unicode-баг»

perlunicode

• строка не всегда рассматриваютсякак Unicode

• это вызывает странные ошибки, для поиска которых требуется время

• use feature ‘unicode_strings’;

• или use 5.12.0

«Unicode-баг»

perlunicode

• строка не всегда рассматриваютсякак Unicode

• это вызывает странные ошибки, для поиска которых требуется время

• use feature ‘unicode_strings’;

• или use 5.12.0

«Unicode-баг»

perldoc

• eval $str

• это октеты или символы?

• что будет, если это включает в себя«use utf8»

• или вы работаете под «use utf8»

Unicode eval

perldoc

• evalbytes $str

• unicode_eval

Unicode eval

perldiag

Мой любимый 5.12-изм?

if (length $input->{new_email}) { $user->update_email(...);}

Use of uninitialized value in lengthat - line 3120.

perldiag

Мой любимый 5.12-изм?

if (length $input->{new_email}) { $user->update_email(...);}

Use of uninitialized value in lengthat - line 3120.

perldiag

Мой любимый 5.12-изм?

if (length $input->{new_email}) { $user->update_email(...);}

Use of uninitialized value in lengthat - line 3120.

perlre

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;

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

perldiag

\N{...}

use 5.16.0;

say "I \N{HEAVY_BLACK_HEART} Queensr" . "\N{LATIN_SMALL_LETTER_Y_WITH_DIAERESIS}"

. "che!";

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

Case Folding

Case Folding

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

Case Folding

if ( fc $foo eq fc $bar ) { ...}

Case Folding

Case Foldinglc ‘ς‘ ➔ ‘ς‘uc ‘ς‘ ➔ ‘Σ‘fc ‘ς‘ ➔ ‘σ‘

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

Case Foldinglc ‘ς‘ ➔ ‘ς‘uc ‘ς‘ ➔ ‘Σ‘fc ‘ς‘ ➔ ‘σ‘

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

Case Foldinglc ‘ς‘ ➔ ‘ς‘uc ‘ς‘ ➔ ‘Σ‘fc ‘ς‘ ➔ ‘σ‘

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

Case Foldinglc ‘ς‘ ➔ ‘ς‘uc ‘ς‘ ➔ ‘Σ‘fc ‘ς‘ ➔ ‘σ‘

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

Case Foldinglc ‘ς‘ ➔ ‘ς‘uc ‘ς‘ ➔ ‘Σ‘fc ‘ς‘ ➔ ‘σ‘

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

Case Foldinglc ‘ς‘ ➔ ‘ς‘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

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

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

✓ ☐ ☐ ¿? ¿?

✓ ☐ ☐ ¿? ¿?

✓ ✓ ☐ ¿? ¿?

✓ ✓ ✓ ¿? ¿?

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

perlre

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

study

perldoc

study

perldoc

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

$str =~ $re; # slow!!study $str; # does stuff$str =~ $re; # fast!!

study

perldoc

my $re = qr{...выражение...};my $str = q{...длинная строка...};

$str =~ $re; # slow!!study $str; # does stuff$str =~ $re; # fast!!

study

perldoc

my $re = qr{...выражение...};my $str = q{...длинная строка...};

$str =~ $re; # медленно!!study $str; # does stuff$str =~ $re; # fast!!

study

perldoc

my $re = qr{...выражение...};my $str = q{...длинная строка...};

$str =~ $re; # медленно!!study $str; # используем$str =~ $re; # fast!!

study

perldoc

my $re = qr{...выражение...};my $str = q{...длинная строка...};

$str =~ $re; # медленно!!study $str; # используем$str =~ $re; # быстро!!

study

perldoc

my $re = qr{...выражение...};my $str = q{...длинная строка...};

$str =~ $re; # медленно, но верно!!study $str; # используем$str =~ $re; # кто знает!!

study

perldoc

my $re = qr{...выражение...};my $str = q{...длинная строка...};

$str =~ $re; # медленно, но верно!!study $str; # используем$str =~ $re; # медленно, но верно!!

Замена модулейModder Modlib

Недавно появившиеся библиотеки в ядре

• JSON

• HTTP::Tiny

• Module::Metadata

• CPAN::Meta

perlmodlib

Недавно удалённые библиотеки

• Devel::DProf

• Switch

• perl4 ядро

• ...и другие

perlmodlib

Удалёнстарый функционал

qw()

perlop

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

qw()

perlop

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

$[

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

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

• разве это не круто?

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

perlvar

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

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

• разве это не круто?

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

perlvar

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

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

• разве это не круто?

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

perlvar

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

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

• разве это не круто?

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

perlvar

$[

perlvar

$[ = 1;

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

$[

perlvar

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

$[

perlvar

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

$[

perlvar

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

defined @arr

Вопросы?

Спасибо за внимание!

Оригинал«What's New in Perl?

v5.10 – v5.16»http://www.slideshare.net/rjbs/whats-new-in-perl-v510-v516