Skip to content

Commit

Permalink
fix blocks; tables
Browse files Browse the repository at this point in the history
  • Loading branch information
zag committed May 13, 2012
1 parent 44e238b commit 140679c
Show file tree
Hide file tree
Showing 11 changed files with 72 additions and 64 deletions.
22 changes: 9 additions & 13 deletions perl6-book.pod
@@ -1,31 +1,30 @@
=begin pod
=begin BOOKINFO
*TITLE Все о Perl 6
*SUBTITLE Справочное руководство
*AUTHOR
=TITLE Все о Perl 6
=SUBTITLE Справочное руководство
=AUTHOR
firstname:Джонатан
surname:Вортингтон
*AUTHOR
=AUTHOR
firstname:Патрик
surname:Мишо
*AUTHOR
=AUTHOR
firstname: Карл
surname:Мэсак
*AUTHOR
=AUTHOR
firstname:Мориц
surname:Ленц
*AUTHOR
=AUTHOR
firstname:Скот
lineage:Джонатан
surname:Даф
*DESCRIPTION
=DESCRIPTION
Данная книга является сборником статей о Perl 6.
*CHANGES
=CHANGES
Sep 19th 2011(v0.7)[zag] Классы и объекты
May 13th 2011(v0.6)[zag] Формат Pod
Expand All @@ -40,8 +39,6 @@ Aug 18th 2010(v0.2)[zag] Предисловие
May 27th 2010(v0.1)[zag] Начальная версия
=end BOOKINFO
=config C<> :allow<E>
=config code :allow<E>
Expand All @@ -65,5 +62,4 @@ May 27th 2010(v0.1)[zag] Начальная версия
Perl 6 Pod chapters from blog http://zag.ru
=Include Pod/pod.pod6
=end pod
8 changes: 5 additions & 3 deletions src/basics.pod
Expand Up @@ -120,7 +120,9 @@ I<dictionary> или I<map>. Получение из хэш-таблицы зн
В программе расчета рейтингов матча, C<%matches> хранит число выигранных матчей каждым игроком. В C<%sets> запоминаются выигранные каждым игроком сеты.
Сигилы указывают на метод доступа к значениям. Переменные с сигилом C<@> предоставляют доступ к значениям по номеру позиции; переменные с сигилом C<%> - по строковому ключу. Сигил C<$>, обычно, ассоциируется с общим контейнером, которым может содержать что угодно и доступ к данным так же может быть организован любым образом. Это значит, что скаляр может даже содержать составные объекты C<Array> и C<Hash>; сигил C<$> указывает на тот факт, что данная переменная должна интерпретироваться как одиночное значение, даже в контексте где ожидаются множественные (как например C<Array> и C<Hash> ).
Сигилы указывают на метод доступа к значениям. Переменные с сигилом C<@> предоставляют доступ к значениям по номеру позиции; переменные с сигилом C<%> - по строковому ключу.
Сигил C<$>, обычно, ассоциируется с общим контейнером, которым может содержать что угодно и доступ к данным так же может быть организован любым образом. Это значит, что скаляр может даже содержать составные объекты C<Array> и C<Hash>; сигил C<$> указывает на тот факт, что данная переменная должна интерпретироваться как одиночное значение, даже в контексте где ожидаются множественные (как например C<Array> и C<Hash> ).
=begin code
Expand Down Expand Up @@ -160,8 +162,8 @@ I<dictionary> или I<map>. Получение из хэш-таблицы зн
=config C<> :allow<E>
=for table :caption('Содержимое переменных')
Переменная Значение
------------|----------
Переменная | Значение
____________|_____________
C<$line> C<'Ana vs Dave E<VERTICAL LINE> 3:0'>
C<$pairing> C<'Ana vs Dave'>
C<$result> C<'3:0'>
Expand Down
23 changes: 11 additions & 12 deletions src/builtins.pod
Expand Up @@ -11,8 +11,7 @@ convert a copy of both C<$a> and C<$b> to numbers (unless they are numbers
already). This implicit conversion is called I<coercion>.
Besides operators, other syntactic elements coerce their elements: C<if> and
C<while> coerce to truth values (C<Bool>), C<for> views things as lists, and so
on.
C<while> coerce to truth values (C<Bool>), C<for> views things as lists, and so on.
=head1 Numbers
Expand Down Expand Up @@ -79,7 +78,7 @@ The following operators are available for all number types:
=begin table :caption('Binary numeric operators')
Operator Description
----------|--------------
____________|________________
C<**> Exponentiation: C<$a**$b> is C<$a> to the power of C<$b>
C<*> multiplication
C</> division
Expand All @@ -90,7 +89,7 @@ The following operators are available for all number types:
=begin table :caption('Unary numeric operators')
Operator Description
----------|--------------
_____________|________________
C<+> conversion to number
C<-> negation
=end table
Expand All @@ -100,7 +99,7 @@ you can write both C<(-5).abs> and C<abs(-5)>.
=begin table :caption('Mathematical functions and methods')
Method Description
----------|--------------
___________|_______________
C<abs> absolute value
C<sqrt> square root
C<log> natural logarithm
Expand Down Expand Up @@ -138,21 +137,21 @@ The following operations are available for strings:
=begin table :caption('Binary string operators')
Operator Description
----------|--------------
____________|______________
C<~> concatenation: C<'a' ~ 'b'> is C<'ab'>
C<x> replication: C<'a' x 2> is C<'aa'>
=end table
=begin table :caption('Unary string operators')
Operator Description
----------|--------------
____________|_______________
C<~> conversion to string: C<~1> becomes C<'1'>
=end table
=begin table :caption('String methods/functions')
Method/function Description
----------------------------|--------------
________________|___________________
C<.chomp> remove trailing newline
C<.substr($start, $length)> extract a part of the string. C<$length> defaults to the rest of the string
C<.chars> number of characters in the string
Expand All @@ -173,18 +172,17 @@ A Boolean value is either C<True> or C<False>. Any value can coerce to a
boolean in boolean context. The rules for deciding if a value is true or false
depend on the type of the value:
=for item Strings
=item Strings
Empty strings and C<"0"> evaluate to C<False>. All other strings evaluate to
C<True>.
=for item Numbers
=item Numbers
All numbers except zero evaluate to C<True>.
=for item Lists and Hashes
=item Lists and Hashes
Container types such as lists and hashes evaluate to C<False> if they are
empty, and to C<True> if they contain at least one value.
Constructs such as C<if> automatically evaluate their conditions in
boolean context. You can force an explicit boolean context by
putting a C<?> in front of an expression. The C<!> prefix negates
Expand All @@ -205,3 +203,4 @@ the boolean value.
=end code
=end pod

2 changes: 2 additions & 0 deletions src/classes-and-objects.pod6
Expand Up @@ -545,7 +545,9 @@ B<Answer:> Чтобы обнаружить повторный вызов мет
=end code
B<3.> Каким образом объект C<Task> может выполнит зависимые задачи параллельно ?
(Подумайте как можно избежать коллизий в "бриллиантовых зависимостях" I<(Пер. - не встречал ранее такого выражения.)>), когда две разных зависимых задачи требуют выполнения одной).
B<Ответ:> Включение параллельного выполнения просто: достаточно заменить вызов метода C<.perform()> для C<@!dependencies;> на C<@!dependencies».perform()>. Однако в таком случае могут возникнуть "гонки" I(race conditions) в случае наличия бриллиантовых зависимостей, когда задача C<A> запускает одновременно C<B> и C<C>, а они в свою очередь запускают C<D> (C<D> запускается дважды). Решение этой проблемы такое же как и в случае с циклическими вызовами в вопросе 2 - ввести атрибут C<$!started>. Заметьте, что в случае параллельного выполнения, вызов die в одной из задач может прервать исполнение других.
=begin code
Expand Down
4 changes: 2 additions & 2 deletions src/grammars.pod
Expand Up @@ -286,14 +286,14 @@ sets the C<ast> attribute of the current match object to C<$thing>.
X<|abstract syntax tree>
X<|AST>
=begin sidebar
=begin comment :sidebar
An abstract syntax tree, or AST, is a data structure which represents the
parsed version of the text. Your grammar describes the structure of the AST:
its root element is the C<TOP> node, which contain children of the allowed
types and so on.
=end sidebar
=end comment
In the case of the JSON parser, the payload is the data structure that the
JSON string represents. For each matching rule, the grammar engine calls an
Expand Down
8 changes: 4 additions & 4 deletions src/multi-dispatch.pod
Expand Up @@ -163,12 +163,12 @@ implementation used to run this test actually executes the where-block twice.
Keep in mind that the number of times the subtype checks blocks execute is
specific to any particular implementation of Perl 6.
=begin sidebar
=begin comment :sidebar
Avoid writing code like this in anything other than example code. Relying on
the side effects of type checks produces unreliable code.
=end sidebar
=end comment
=head1 Narrowness
Expand Down Expand Up @@ -465,12 +465,12 @@ which prevents accidental overriding of built-insN<One of the very rare
exceptions is the smart match operator C<< infix:<~~> >> which is not easily
overloadable. Instead it redispatches to overloadable multi methods.>.
=begin sidebar
=begin comment :sidebar
To hide all candidates of a multi and replace them by another sub, declare it
as C<only sub YourSub>. At the time of writing, no compiler supports this.
=end sidebar
=end comment
=head1 Toying with the candidate list
Expand Down
10 changes: 6 additions & 4 deletions src/operators.pod
Expand Up @@ -137,7 +137,9 @@ key twice.>
}
=end code
Данный код циклически обходит весь список C<@scores>, связывая каждый из элементов со специальной переменной C<$_>. Для каждого элемента используется встроенная функция C<printf> X<|printf>, которая печатает на экране имя игрока и строку диаграммы. Данная функция похожа на C<printf> в языках C и Perl 5. Она получает строку форматирования, которая описывает каким образом печатать следующие за ней параметры. Если C<$label-area-width> равна 8, то строка форматирования будет C<"%-8s%s\n">. Это значит, что строка C<%s> занимает 8 позиций (C<'8'>) и выравнена по левому краю, за ней следует еще строка и символ новой строки C<'\n'>.
Данный код циклически обходит весь список C<@scores>, связывая каждый из элементов со специальной переменной C<$_>. Для каждого элемента используется встроенная функция C<printf> X<|printf>, которая печатает на экране имя игрока и строку диаграммы.
Данная функция похожа на C<printf> в языках C и Perl 5. Она получает строку форматирования, которая описывает каким образом печатать следующие за ней параметры. Если C<$label-area-width> равна 8, то строка форматирования будет C<"%-8s%s\n">. Это значит, что строка C<%s> занимает 8 позиций (C<'8'>) и выравнена по левому краю, за ней следует еще строка и символ новой строки C<'\n'>.
В нашем случае первой строкой является имя игрока. второй - строка диаграммы.
Инфиксный оператор C<x>, или I<X<оператор повторения| оператор,x; оператор повторения>>, формирует строку столбца. Он возвращает строку, состоящую из левого операнда, повторенного число раз, заданное правым операндом. То есть C<'ab' x 3> вернет строку C<'ababab'>. C<.value> возвращает значение текущей пары, C<($unit * .value)> умножает его на C<$unit>, и C<'X' x ($unit * .value)> возвращает строку с требуемым количеством символов.
Expand Down Expand Up @@ -176,7 +178,7 @@ I<X<Правила приоритетности| приоритетность,
=begin table :caption("Таблица приоритетов")
Пример Имя
----------------|------------------
_________________|__________________
C<(), 42.5> term
C<42.rand> вызовы методов и postcircumfixes
C<$x++> автоинкремент и автодекремент
Expand Down Expand Up @@ -291,7 +293,7 @@ X<|eq;operator, eq>
=begin table :caption("Операторы и сравнения")
Числовые Строковые Значение
----------------|--------------------|-----------
_________________|______________________|______________________________
== eq равно I<(equals)>
!= ne не равно I<(not equal)>
!== !eq не равно I<(not equal)>
Expand All @@ -308,7 +310,7 @@ X<|оператор, !=;!=>
X<|ne;оператор, ne>
X<|eq;оператор,eq>
C<!=> на самом деле более удобная форма для C<!==>, который в свою очередб представляет собой объединеие метаоператора C<!> и инфиксного оператора C<==>. Такое же обяснение приминительно к C<ne> и C<!eq>.
C<!=> на самом деле более удобная форма для C<!==>, который в свою очередь представляет собой объединеие метаоператора C<!> и инфиксного оператора C<==>. Такое же обяснение приминительно к C<ne> и C<!eq>.
=head2 Three-way сравнение
Expand Down
7 changes: 5 additions & 2 deletions src/preface.pod
Expand Up @@ -10,7 +10,10 @@ Perl 6 универсален, интуитивен и гибок. Он охва
=head1 Perl должен оставаться Perl
Perl 6 по прежнему остается Perl. Что это означает ? Конечно же это не значит, что Perl 6 обладает такой же функциональностью или синтаксически совместим с Perl 5. В таком случае это была бы очередная версия Perl 5. Perl является философией и оба языка, Perl 5 и Perl 6, разделяют ее. Согласно этой философии существует больше одного способа достичь результата , а также простые вещи должны оставаться простыми, а сложные - возможными. Эти принципы связаны с прошлым, настоящим и будущим Perl и определяют фундаментальное предназначение Perl 6. В Perl 6 легкие вещи стали более легкими, а трудные - более возможными.
Perl 6 по прежнему остается Perl. Что это означает ? Конечно же это не значит, что Perl 6 обладает такой же функциональностью или синтаксически совместим с Perl 5. В таком случае это была бы очередная версия Perl 5.
Perl является философией и оба языка, Perl 5 и Perl 6, разделяют ее. Согласно этой философии существует больше одного способа достичь результата , а также простые вещи должны оставаться простыми, а сложные - возможными.
Эти принципы связаны с прошлым, настоящим и будущим Perl и определяют фундаментальное предназначение Perl 6. В Perl 6 легкие вещи стали более легкими, а трудные - более возможными.
=head1 Реализации Perl 6
Expand All @@ -24,7 +27,7 @@ Perl 6 по прежнему остается Perl. Что это означае
Если вы являетесь пользователем FreeBSD, то для установки достаточно выполнить команду:
=output
pkg_add -r rakudo
pkg_add -r rakudB<o>
Проверить правильность установки Rakudo можно с помощью команды:
Expand Down
18 changes: 9 additions & 9 deletions src/regexes.pod
Expand Up @@ -96,14 +96,14 @@ single, arbitrary character:
This prints:
=begin screen
=begin output
spell contains pell
superlative contains perl
openly contains penl
no match for stuff
=end screen
=end output
X<|$/>
X<|match object>
Expand Down Expand Up @@ -142,7 +142,7 @@ X<|regex, \V>
=begin table :caption('Backslash sequences and their meaning')
Symbol Description Examples
--------|----------------|---------
________|_______________|_____________
C<\w> word character l, ö, 3, _
C<\d> digit 0, 1
C<\s> whitespace (tab), (blank), (newline)
Expand Down Expand Up @@ -327,7 +327,7 @@ an C<a>, and C<m/ ^ a $ /> matches strings that consist only of an C<a>.
=begin table :caption('Regex anchors')
Anchor Meaning
--------|-------------
_________|___________
C<^> start of string
C<$> end of string
C<^^> start of a line
Expand Down Expand Up @@ -382,12 +382,12 @@ list of other match objects:
This prints:
=begin screen
=begin output
list: eggs | milk | sugar
end: flour
=end screen
=end output
The first capture, C<(\w+)>, was quantified, so C<$/[0]> contains a list of
words. The code calls C<.join> to turn it into a string. Regardless of how
Expand Down Expand Up @@ -683,7 +683,7 @@ assertions, though they won't be as efficient.
=begin table :caption('Emulation of anchors with look-around assertions')
Anchor Meaning Equivalent Assertion
--------|--------------------|---------
_________|________________|______________________
C<^> start of string C<< <!after .> >>
C<^^> start of line C<< <?after ^ E<VERTICAL LINE> \n > >>
C<$> end of string C<< <!before .> >>
Expand Down Expand Up @@ -739,7 +739,7 @@ position (C<$m.orig.substr(0, $m.from)>), splitting it by newlines, and
counting the elements. It calculates the column by searching backwards from
the match position and calculating the difference to the match position.
=begin sidebar
=begin comment :sidebar
X<|index>
X<|rindex>
Expand All @@ -749,7 +749,7 @@ position of the search string. The C<rindex> method does the same, but
searches backwards from the end of the string, so it finds the position of the
final occurrence of the substring.
=end sidebar
=end comment
X<|Match, access as a hash>
X<|named captures>
Expand Down

0 comments on commit 140679c

Please sign in to comment.