Skip to content
Open
Changes from 1 commit
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Update perlsecret.ru.pod
  • Loading branch information
mishin committed Oct 20, 2014
commit 8f45c23f1c48e9a7ff404799e7c7f50cf4d3b49f
119 changes: 58 additions & 61 deletions lib/perlsecret.ru.pod
Original file line number Diff line number Diff line change
Expand Up @@ -461,114 +461,111 @@ https://ru.wikipedia.org/wiki/Дополнительный_код_(предст
Use of implicit split to @_ is deprecated
Использование неявного сплита для @_ не рекомендуется

Using C<=()=> to force scalar context on the left side (to get the number
of substrings) and list context on the right side (to avoid the deprecated
not-in-list-context construct) seems like the proper solution:
Использование C<=()=> для приведения к скалярному контексту на левой стороне (чтобы получить число
подстрок) и списочный контекст на правой стороне (чтобы избежать устаревшую
конструкцию не в списочном контексте) кажется, вот правильное решение:

my $count =()= split /:/, $string;

It does not warn indeed, but always returns C<1> (which is usually wrong).
Она действительно не предупреждает, но всегда возвращает C<1>(что вообщето неправильно).

The reason is that C<split()> never splits to more fields than necessary.
And the compiler interprets storing the results in C<()> as not caring
about the results, so C<split()> will B<not split the string at all>,
and thus return the full string, which gives a list of only one element
in scalar context, hence the C<1>.
Причина того, что C<split()> никогда не разбивается больше полей, чем необходимо.
И компилятор интерпретирует, сохранение результатов в C<()> , не заботясь о
о результатах, так C<split()> не будет B<разбивать строку на всё>,
и таким образом вернуть полную строку, которая дает список только одного элемента
в скалярном контексте, следовательно C<1>.

You have two options to address this. First, you can override C<split()>'s
optimization by explicitly asking it to split into an unlimited number of
fields:
У вас есть два варианта решения этой проблемы. Во-первых можно переопределить C<split()>
оптимизацию, явно задавая его разделить на неограниченное число
полей:

my $count =()= split /:/, $string, -1;

Or else you can defeat the optimization by using another secret operator
instead, the I<baby cart>:
Или же вы можете победить оптимизации с помощью другого секретного оператора
вместо этого I<детской коляской>:

my $count = @{[ split /:/, $string ]};

This causes C<split()> to detect that its caller can store any number of
fields, thus it will actually do the work before the anonymous
array is thrown away after being used in scalar context.
Это понуждает C<split()> обнаружить, что вызывающий объект может хранить любое количество
полей, таким образом он будет на самом деле делать работу до того, как анонимный
массив выбрасывается после использования в скалярном контексте.


=head2 Flaming X-Wing
=head2 Пылающий X-Wing Истребитель (Flaming X-Wing)

=<>=~

Discovered by Philippe Bruhat, 2007.
Открыт Филиппом Брюа, 2007.

This operator applies a regular expression to a single line of input
and assigns the captured values to the expression to its left-hand side.
Этот оператор применяет регулярное выражение к одной строке ввода
и назначает захваченных значения в выражение на его левой стороне.

# pick named fields from input
# поймать имена полей из входящего потока (input)
@data{@fields} =<>=~ $regexp;

The above statement decomposes as follows: C<=~> provides scalar context
to C<< <> >> on its left, thus matching on a single line of input.
If the regular expression contains captures, having an array-like
structure on the left side of the C<=> provides list context, and the
captured data is assigned to the structure.
Объясняетя вышеназванное выражение: C<=~> обеспечивает скалярный контекст
для левой стороны C<< <> >> таким образом, что ищет во входящей строке.
Если регулярное выражение содержит захваты, имеющие структуру массива
с левой стороны, C<=> обеспечивает списочный контекст и
захваченные данные назначаются структуре.

This operator is also a container. So the X-Wing can have a pilot!
Этот оператор также является контейнером. Поэтому X-Wing может иметь пилота!

# use the source, Luke!
# используй исходный текст, Люк!
$luke = \*DATA;
@data{@fields} =<$luke>=~ $regexp;

=head2 Kite
=head2 Кайт (Kite)

~~<>

Discovered by Philippe Bruhat, 2012.
(Alternate nickname: "sperm")

This operator is actually a combination of the inchworm and the diamond
operator. It provides scalar context to the C<readline()> builtin, thus
returning a single line of input.
Открыт Филиппом Бруа, 2012.
(Альтернативное название: "сперматазоид")

It's only useful in list context (since C<< <> >> already returns a
single line of input in scalar and void contexts), for example for getting
several lines at once:
Этот оператор на самом деле сочетание Дюймочервя и бриллиантового
оператора. Он обеспечивает скалярный контекст встроенному C<readline()>, таким образом,
возвращая одну строку ввода.

@triplets = ( ~~<>, ~~<>, ~~<> ); # three sperms in a single egg?
Это полезно только в списочном контексте (так как C<< <> >> уже возвращает
единую линию ввода в скалярном и пустом контекстах), например, для получения
сразу несколько линий:

Like the other operators based on bracketing constructs, the kite is a
container, and can carry a payload (a file handle, in this case).
@triplets = ( ~~<>, ~~<>, ~~<> ); # три спермы в одно яйцо?

Note that when the filehandle is exhausted, the kite operator will
return the empty string instead of C<undef>.
Как и другие операторы, основанные на скобочных конструкциях , кайт
контейнер и может нести полезную нагрузку (в данном случае, дескриптор файла).

Mnemonic: It provides a feature that is tied to one line, a string,
as it were. (Tye McQueen in L<http://www.perlmonks.org/?node_id=959906>).
Обратите внимание, что когда дескриптор файла дочитан до конца, оператор кайт будет
возвращать пустую строку вместо C <undef>.

Мнемоника: Он обеспечивает функцию, которая привязана к одной строке, строке,
как она была. (Tye Маккуин в L<http://www.perlmonks.org/?node_id=959906>).

=head2 Ornate double-bladed sword
=head2 Богатый двухлезвийный меч (Ornate double-bladed sword)

<<m=~m>>
m
;

Created by Abigail, 2003, for comp.lang.perl.misc.
Создан Абигалем, 2003, for comp.lang.perl.misc.

This operator provides multi-line comments, by clever use
of heredoc syntax and beautiful symmetry.
Quoting C<< <slrnb382jc.tfm.abigail@alexandra.abigail.nl> >>:
Этот оператор обеспечивает многострочные комментарии, путем разумного использования
heredoc-синтаксиса и красивой симметрии.
Цитата C<< <slrnb382jc.tfm.abigail@alexandra.abigail.nl> >>:

<<m=~m>>
Use the secret operator on the previous line.
Put your comments here.
Lots and lots of comments.
Используйте тайный оператор в предыдущей строке.
Запишите ваши комментарии здесь.
Много и много комментов.

You can even use blank lines.
Finish with a single
Вы даже можете использовать пустые строки.
Закончим с одной
m
;

The "ornament" is the C<m> ribbon with the C<;> throwing blade attached
to it.
"Орнамент" C<m> ленты с C<;> бросает меч, привязанный к нему.

Note that the "commented" text is actually a double-quoted string in
void context, which can have some side effects.
Обратите внимание, что "комментируемый" текст на самом деле строка в двойных кавычках в
пустом контексте, что может иметь некоторые побочные эффекты.

=head2 Screwdriver operators

Expand Down