Perl 6

Perl 6 Update (YAPC::EU 2007)

Совместная презентация Дамиана Конвея и Ларри Уолла Perl 6 Update.

YAPC::EU 2007

Ниже — мой конспект.

несколько версий одного и того же модуля
class TreeBark:name:auth;
class DogBark:name:auth;
my $c = TreeBark:new()
--
$this=$code && #{comment} $code_too;
--
sek_jey ('C#')
if %rain
{
$xxx;
}
если комментировать все до начала блока
можно закомментировать блока
#{ --- неверно если начинается в начале строки ((( или надо поставить ##)
...
}
--
$obj\    .method()
%hohoa\
\
         нельзя ставить пробелы но можно \
тн unspace (в отличие от whitespace)
--
$_ is no longer the dafault variable
for (@data) {
chomp;   # в 6-м ничего не делает
print;
}
--
for(@data){
.=chomp;
.print;
}  
unary dot call the method what was described with $_;
--
.= is another new feature
.= x ==== whatever = whatever . x
--
.=   это reflecsive method call  
--
поведение по умолчанию надо писать явно
--
for "zip"
my %hash  = @keys Z @values;
for @names Z @addrs -> $name, $addr{
say "$name lives at $addr";
}
two or more lists in pararell
если разной длины - остонавливается на самом коротком 
--
for @names Z (@addrs, *) -> $name, $addr{
say "$name lives at $addr";
}
lazely evaluated
* is a 'whatever' operator
* here replicates the final value
for @names Z (@addrs, @addrs[*-1] xx *) -> $name, $addr{
say "$name lives at $addr";
}
--
или так
for @names Z (@addrs, '????' xx *) -> $name, $addr{
say "$name lives at $addr";
}
--
for roundrobin(@q1; @q2; @q3) -> $next{
serve($next);
}
--
$largest = $x max $y max $z
minimum and maximum operators
@scores_clipped = @scores »min» 100;   
» если стоит около оператора, превращает его в оператор над массивами
--
for @values -> $val{
$first_val min= $val;
$last_val m
$first_val = [min] @vals;   a reduction over this operator
функция сравнения (попарная) зависит от типа аргументов
--
my @pre_squares  = (1..100) ** 2 - 1
# 0,3,8, 15, 24, ....9999
lazily
my @pre_squars = (1..*) ** 2 - 1
# 0,3,8,15,....9999,....10200, 10403
--
-r
-w
-x etc
match filehandle against a pair
if $file ~~ :r {say}
while $file ~~ 
while $fuile.:w
given $file {
when :r | :w | :x {...  или any()
when :w & :!r
--
метаоператор X
circumfix X..X
X~X <1 2>    # ('a1','a2','b1','b2')
max (@a X*X @b)   every by every
X,X (1,2) X,X 
X (1,2) X 
max (@a X*X @b)
--
y/// synonym for tr/// is no more
--
CONTROL STRUCTURES
main subroutine --- interpreter starts at first exec
@*ARGS (not ARGV)
после первых инструкций вызовется MAIN если есть
--
sub MAIN ($dir, :$verbouse, *%other, *@filemames
backup.pl --verbose ~/back *.pm
~/back идет в $dir, *.pm в filename
backup.pl --dir=~/bak
-- multi MAIN ($from where /\.pm$/ , $to)
multi MAIN ($from, $to, :$fast)
multi MAIN ($from, $to)
---
если нет подходящего M`Ain
calls USAGE() instead
или автогенерация неправильного использования
--
new loop type
always iterates at least once
repeat{
print "Name:";
$name = =<>;
} while $name !~~ /\S/;
repeat while $name !~~ /\S/{
}
--
repeat{
} until 
repeat until{
}
repeat until $cmd eq 'exit'{
...
redo if $cmd !~~ /\S/'
...
}
do{
}
while ...
repeat{
}
--
say "Accepted {.name} ({.score})"
if .score >= 50
for @candidates;
%frequency{$_}++ unless /^ \#/ for =<>;
can be used inside parens
--
каждая контрол-инструкция возвращает результат (последнее statement in the loop)
@small_primes_squared = ($_ ** 2 if .is_prime for 1..1000);
--
@versioned_files = ({"$^file.$^num"} for @files X 1..100);
^ - srcondary sigils 
--
for 0 <= each(@scores) < 50{
say "failed: $_";
}
each использована в сравнении
то же что grep {0 <= $_ < 50} 
--
lazy + serial: %hash = map {$_, get_val($_)}, @arr;
eager+serial: %hash = eager map {....}
eager+parallel: %hash= hyper map {}
positronic? :-)
--
REGEXES
если юникод говорит что это literal это будет литералом
non-identifier glyphs are metasyntactic or literal when escaped
whitespaces игнорируются если нет флага у рег. выр.
/ '' /
(см. кавычки)
--
$currency ~~ / '$' |   'L$' | ... /;
или так $currency ~~ / < $ ... LS > /  нужен пробел после первой <
--
/ I said no+ / # noooooooooo
/I said 'no'+ / #nonononono
/I said 'no '+ / #no no no no
--
| (or) no longer matches the leftmost successive match
в Perl 6 - самую длинную совпавшую
если две одинаковой длинны, возвращается левая
|| short-circuiting
--
"barnyard" ~~ / bar | barn | barny/;   #barny
"..." ~~ / bar || barb || barny/; #bar
"..." ~~ /bar | bar.*d | barny/;    #barny
"..." ~~ /bar || bar.*d || barny/; #bar
--
/ x{5} / -- perl 5
/xxxxx/
perl6:
/x**5/
perl5: /(?: \d+, ){2} / x
perl6: /[ \d \, ] ** 2/   или {2..*}
или **{$min_rep .. max_rep()}
{} это код
--
/(\d+) \: (<[ACGT]>**{$0})/ ---$0 начинается с нуля
--
$*PROG -- вместо $0 (имя программы)
--
/ [ \d+ ] ** ',' / 
--
(см фото)
--
<( and )> metasyntax
/ bar / (after и before) -- lookbehind
или /foo <( bar )> baz / -- не lookbehind (притвориться, что смотрели назад или вперед)
--
как и раньше
s/foo/bar/;
s!foo!bar!;
s[foo] дает l-value
s[foo] = 'bar';
s[foo] = func($0)
s[foo] ~= 'd'; foo->food (~= это конкатенация)
s[ \d+] *= 2;  #double your money
s[$ <( \d+ ] *= 2;
если нужно применить к конкретной переменной, надо ~~
--
arrays starts always from 0
--
my @calendar[12]   #  0..11
если выйти за границы -- die
--
my @virtures[*]   не важно какой размер
--
my @calendar[12;31;24];
--
my @calendar[12;*;24];
say @calenday[$month;$day; $hour]
@xxx = @calendar[0..^6;*;9..17] --- slice
--
my @spacetime[100;100;100;**] -- at least three dimentions
--
@array[*-N]  (то что в perl5 [-1])
[*-7]
[*] -- элемент за последним
[*+1]
--
USER-DEFINES INDICES
my @dwarves{1..7} (фигурные скобки)
my @seasons{};
my @signs{7..*};
@dwarves{7} = "Doc";
say @calendar{Jan;13;10};
или @dwarves<<7>> = "Doc"; (hash-notation)
--
my @drinks
if @drinks[2]
--
DOCUMENTATION
extend the Pod
underlying DOM

yapceu07 — 29 августа 2007