From 2fbf765eda6d0c125be6765cd0f8b4675d81d716 Mon Sep 17 00:00:00 2001 From: Nikolay Mishin Date: Fri, 3 Oct 2014 10:22:03 +0400 Subject: [PATCH 01/28] Create perlsecret.ru.pod --- lib/perlsecret.ru.pod | 968 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 968 insertions(+) create mode 100644 lib/perlsecret.ru.pod diff --git a/lib/perlsecret.ru.pod b/lib/perlsecret.ru.pod new file mode 100644 index 0000000..7f8533f --- /dev/null +++ b/lib/perlsecret.ru.pod @@ -0,0 +1,968 @@ +=encoding utf8 + +=head1 NAME + +perlsecret - Perl secret operators and constants + +=head1 SYNOPSIS + +Perl secret operators: + + Operator Nickname Function + ====================================================== + 0+ Venus numification + @{[ ]} Babycart list interpolation + !! Bang bang boolean conversion + }{ Eskimo greeting END block for one-liners + ~~ Inchworm scalar + ~- Inchworm on a stick high-precedence decrement + -~ Inchworm on a stick high-precedence increment + -+- Space station high-precedence numification + =( )= Goatse scalar / list context + =< >=~ Flaming X-Wing match input, assign captures + ~~<> Kite a single line of input + <> m ; Ornate double-bladed sword multiline comment + -=! -=!! Flathead conditional decrement + +=! +=!! Phillips conditional increment + x=! x=!! Pozidriv conditional reset to '' + *=! *=!! Torx conditional reset to 0 + ,=> Winking fat comma non-stringifying fat comma + ()x!! Enterprise boolean list squash + 0+!! Key to the truth numeric boolean conversion + ||() Abbott and Costello remove false scalar from list + //() Leaning Abbott and Costello remove undef from list + +Perl secret constants: + + Constant Nickname Value + ====================================================== + <=><=><=> Space fleet 0 + <~> Amphisbaena $ENV{HOME} + +=head1 DESCRIPTION + +Perl has a long tradition of giving nicknames to some of its operators +(possibly a form of Huffmanisation). These nicknames are based on the +appearance of the operator, rather than its function. +The well-known examples +are the I (C<< <> >>), nicknamed by Geneva Wall +and the I (C<< <=> >>), nicknamed by Randal Schwartz. +Some lesser known Perl operators with a nickname are the I +(C<< => >>) and I (C<< ... >>). + +The Perl "I" have been discovered (or created) by +Perl obfuscators and golfers, usually when looking for a shorter way to +perform a given operation. +Secret operators are not actually secret, and they are not actually +operators either. The perl parser does not specifically recognise them, +and no one is trying to hide them from you. +But they are like operators in the sense that these Perl programmers see +them often enough to recognize them without thinking about their smaller +parts, and eventually add them to their toolbox. +And they are like secrets in the sense that they have to be discovered by +their future user (or be transmitted by a fellow programmer), because they +are not explicitly described in the Perl core documentation. + +Because secret operators are not operators they don't have real names, and +so they need nicknames. +Like the above Perl operators, their name is usually related to their shape. + +The term "secret operator" was probably coined by Abigail in a +C post in January 2003. + +=head2 A word of warning + +Many of those "operators" are not suitable for production code, +because they are obscure to the uninitiated, although some are just names +for common idioms. The really secret operators are used by golfers, +obfuscators and people who like +to have fun with their favorite programming language. + +You're welcome to try these at home, but they might not be safe for work! + +=head1 SECRET OPERATORS + +The following section presents the Perl secret operators, with +some historical context, an explanation of how they work and +examples of use. + +=head2 Venus + + 0+ + +0 + +The I operator is a name given to a very common idiom. It performs +the numification of the value on its +right/left, depending of the version used. (This is accomplished by +using the identity element for the addition). + + print 0+ '23a'; # 23 + + print 0+ '3.00'; # 3 + + print 0+ '1.2e3'; # 1200 + + print 0+ '42 EUR'; # 42 + + print 0+ 'two cents'; # 0 + + $ref = []; + print 0+ $ref, ' ', "$ref"; # 164094424 ARRAY(0x9c7e1d8) + + print 0+ $!, ' ', $!; # 2 No such file or directory + + +Note that C<0+> is the method name used for "numeric conversion" by +the C module. + +=head2 Baby cart + + @{[ ]} + +Discovered by Larry Wall, 1994. +(Alternate nicknames: "shopping-trolley", "pram", "turtle") + +The I operator performs list interpolation inside a string. +The list items are separated by the value of C<$">. + + # SQL in a heredoc + local $" = ','; + my $sth = $self->execute( << "SQL" ); + SELECT id, name, salary + FROM employee + WHERE id IN (@{[ keys %employee ]}) + SQL + + # process args in %arg + # and spit out the unknown ones + die "Uuh?: @{[ sort keys %arg ]}\n" + +Another use case is for breaking aliasing (i.e. make a copy); for example +to avoid the C fatal error +when running such code: + + for (qw( 1 2 3 )) { + $_ = $_ * $_; # contrived + print "square: $_\n"; + } + +With the babycart, the topic is an actually modifiable copied scalar. + + for ( @{[ qw( 1 2 3 ) ]} ) { + $_ = $_ * $_; # contrived + print "square: $_\n"; + } + +This is a I, or I operator. The expression +inside the C<[]> is run in list context, stored in an anonymous array, +which is immediately dereferenced by C<@{}>. + +You will see this occasionally in production code. + +=head2 Bang bang + + !! + +This operator was in common usage by C programmers even before Perl existed. +It performs boolean conversion, by performing logical negation +twice. + + my $true = !! 'a string'; # now 1 + my $false = !! undef; # now '' + +=head2 Eskimo greeting + + }{ + +(Alternate nickname: "butterfly") + +Discovered by Abigail, in 1997. + +The I operator is an C block for one-liners. + +The following program counts and prints the number of lines in the input: + + $ perl -lne '}{print$.' + +The Eskimo greeting abuses the way the B<-p> and B<-n> options generate +Perl code (as shown by using the C module): + + $ perl -MO=Deparse -lne '}{print$.' + -e syntax OK + BEGIN { $/ = "\n"; $\ = "\n"; } + LINE: while (defined($_ = )) { + chomp $_; + } + { + print $.; + } + +The discovery was done after The Perl Journal published an interview with +Chip Salzenberg, in which he explained what hack perl uses to implement +C<< -p >> and C<< -n >>. + +Ethnographic note: in modern Western culture, an eskimo kiss is the act +of pressing the tip of one's nose against another's. It is loosely based +on a traditional Inuit greeting called a I, that early explorers +of the Arctic dubbed "Eskimo kissing" when they first witnessed it. The +kunik itself is not a kiss, not erotic, and simply of form of affectionate +greeting. + +=head2 Inchworm + + ~~ + +This operator is basically a shorter C (shaves 4 characters!) +using the same idea as the secret bang bang operator. + + $ perl -Esay~~localtime + Tue Mar 13 19:53:25 2012 + +The inchworm looks very much like the smart-match operator introduced +in Perl 5.10, but since it's actually a sequence of two unary operators, +the Perl parser can't mix it up with the binary smart-match. + +Note that Perl's C<~> is operand sensitive: if its operand has a numeric +value (either because it was assigned a number, the result of a numeric +operation, or had been used in numeric context), it is a numeric bitwise +negation (first implicitly converting to unsigned integer (UV), or under +the scope of C>, signed integer (IV)); otherwise it is a +string bitwise negation. + +And this explains how it differs from C. Instead of forcing the operand +into some kind of boolean, it forces it into some kind of either string or +number (depending on the operand). + +Thus, for most inputs, the inchworm acts just like C. + +Examples of exceptions: + + # floating point + $x = 1.23; + print ~~$x; # 1 + + # string used in numeric context + $x = "1.23"; + print ~~$x if $x != 0; # 1 + + # integer out of range + use Config '%Config'; + + $x = 2**( 8 * $Config{uvsize} ); + print ~~$x; # UV_MAX + + $x = -1; + print ~~$x; # UV_MAX + + $x = 2**( 8 * $Config{uvsize} - 1 ); + { + use integer; + print ~~$x; # IV_MIN + } + + $x = -2**( 8 * $Config{uvsize} - 1 ) - 1; + { + use integer; + print ~~$x; # IV_MIN + } + +But it is also handy as a shorthand to get stringification from objects that +overload it in some useful way: + + use DateTime; + use JSON; + my $now = DateTime->now; + print encode_json { time => ~~$now }; + +=head2 Inchworm on a stick + + ~- + -~ + +Discovered by Ton Hospel, 2002. + +These two operators perform a high-precedence decrement (C<~->) and +high-precedence increment (C<-~>) on integers (on a two's-complement +architecture). It's a trick that assembly language programmers have +been using for decades. + +In C, Python and Ruby, they work on all integers. Due to how C<~> +is implemented in Perl (a little known fact is that Perl's bitwise +operators cast operands to unsigned integers without C> +and to signed integers with C), this pair of +secret operators is limited to signed integers. +It's actually even more limited by default: C<~-> only decrements integers +greater than 0, and C<-~> only increments integers lesser than 0. To +get the inchworms on a stick to work on all signed integers, they must be used +under the scope of C, so that signed integers are used everywhere in +bitwise operations. + +This golfing technique allows to get rid of a pair of parentheses: + + $y = ~-$x * 4; # identical to $y = ($x-1)*4; + + +Here's the proof: + + $x - 1 == - ( -$x ) - 1 + +In two's complement architectures, to get the opposite of a number, +all you need to do is flip all bits, and add 1. I.e., + + -$i == ~$i + 1 + +Using this to replace C< - ( -$x ) > in the above identity, we get: + + $x - 1 == ( ~-$x + 1 ) - 1 + +And after eliminating the ones from the equation, + + $x - 1 == ~-$x + +QED. + +For C<-~>, the proof is similar: + + $x + 1 == - ( -$x ) + 1 + + $x + 1 == - ( ~$x + 1 ) + 1 + + $x + 1 == -~$x - 1 + 1 + + $x + 1 == -~$x + + +In both versions, the high precedence comes from the fact that C<~> +and unary C<-> both have higher precedence than all other arithmetic +operators (except C<**>). + +Mnemonic: the backwards-facing inchworm on a stick (C<~->) decrements, +and the forward-facing inchworm on a stick (C<-~>) increments. + + +=head2 Space station + + -+- + +Discovered by Alistair McGlinchy, 2005. + +This operator performs a high precedence numification. + + print -+- '23a'; # 23 + + print -+- '3.00'; # 3 + + print -+- '1.2e3'; # 1200 + + print -+- '42 EUR'; # 42 + + $ref = []; + print -+- $ref, ' ', "$ref"; # 151097816 ARRAY(0x90191d8) + + print -+- $!, ' ', $!; # 2 No such file or directory + +At first, this looks exactly like the Venus operator. However, because +the Venus operator uses a binary C<+>, it has a lower precedence than +the multiplicative operators like C<*> or C. On the other hand, +the space station operator is the concatenation of three unary operators, +and therefore has higher precedence. + +In the following example, we'll try to print the numification of +the string C<'20GBP'> (i.e. C<'20'>) repeated three times. + + # wrong: prints the numification of '20GBP20GBP20GBP' + print 0+ '20GBP' x 3; # 20 + + # wrong: does the equivalent of ( print '20' ) x 3 + print( 0+ '20GBP' ) x 3; # 20 + + # right: but too lengthy, too lispy + print( ( 0 + '20GBP' ) x 3 ); # 202020 + + # right: uses the space station operator + print -+- '20GBP' x 3; # 202020 + +However, because unary minus simply replace the initial C<-> or C<+> of a string +by its counterpart, the space station does B numify I +or I: + + print -+- 'two cents'; # +two cents + + print -+- '-2B' x 5; # -2B-2B-2B-2B-2B + +In the above example, C<-+- '-2B'> produces the string C<'-2B'>, +whereas C<0+ '-2B'> would have given the expected number (C<-2>). + + +=head2 Goatse + + =( )= + +(Alternate nickname: "Saturn") + +If you don't understand the name of this operator, consider yourself lucky. +You are advised B to search the Internet for a visual explanation. + +The goatse operator provides a list context to its right side and +returns the number of elements to its left side. +Note that the left side must provide a scalar context; obviously, a list +context on the left side will receive the empty list in the middle. + +The explanation is that a list assignment in scalar context returns the +number of elements on the right-hand side of the assignment, no matter +how many of those elements were actually assigned to variables. In this +case, all the elements on the right are simply assigned to an empty list +(and therefore discarded). + + # count the words in $_ + $n =()= /word1|word2|word3/g; + + # $n = 1 + $n =()= "abababab" =~ /a/; + + # $n = 4 + $n =()= "abababab" =~ /a/g; + +The goatse operator is a container (sic), so it can also be used to +assign values from the right-hand side to the variables inside it. + + # $n = 4; $b = 'a' + $n =($b)= "abababab" =~ /a/g; + + # $n = 4; @c = qw( a a a a ) + $n =(@c)= "abababab" =~ /a/g; + +In some cases, the full goaste is not needed, because there is no need +to store the value in a variable. The side-effect of list assignment in +scalar context can be obtained with a I (C<()=>) +used in a scalar context provided by some other mean than assignement +to a scalar. +For example: + + # remove empty array refs + @arrays = ( [], [1], [ 1, 2 ], [], [ 5 .. 9 ] ); + + # @filled = ( [1], [ 1, 2 ], [ 5 .. 9 ] ); + @filled = grep +()= @$_, @arrays; + +(The C<+> is in the above line is a no-op, used to tell C that the +parentheses are not enclosing its arguments.) + +Here's a convoluted example where C<=()=> seems to be the proper +construct to use, but it's actually another secret operator that +really does the trick. + +Imagine you want to know in how many elements C<< split() >> would split +a string, but do not care about the elements themselves. Using C +in scalar context: + + my $count = split /:/, $string; + +Gives the correct answer, but also a warning: + + 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: + + my $count =()= split /:/, $string; + +It does not warn indeed, but always returns C<1> (which is usually wrong). + +The reason is that C never splits to more fields than necessary. +And the compiler interprets storing the results in C<()> as not caring +about the results, so C will B, +and thus return the full string, which gives a list of only one element +in scalar context, hence the C<1>. + +You have two options to address this. First, you can override C's +optimization by explicitly asking it to split into an unlimited number of +fields: + + my $count =()= split /:/, $string, -1; + +Or else you can defeat the optimization by using another secret operator +instead, the I: + + my $count = @{[ split /:/, $string ]}; + +This causes C 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. + + +=head2 Flaming X-Wing + + =<>=~ + +Discovered by Philippe Bruhat, 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 + @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. + +This operator is also a container. So the X-Wing can have a pilot! + + # use the source, Luke! + $luke = \*DATA; + @data{@fields} =<$luke>=~ $regexp; + +=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 builtin, thus +returning a single line of input. + +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: + + @triplets = ( ~~<>, ~~<>, ~~<> ); # three sperms in a single egg? + +Like the other operators based on bracketing constructs, the kite is a +container, and can carry a payload (a file handle, in this case). + +Note that when the filehandle is exhausted, the kite operator will +return the empty string instead of C. + +Mnemonic: It provides a feature that is tied to one line, a string, +as it were. (Tye McQueen in L). + + +=head2 Ornate double-bladed sword + + <> + m + ; + +Created by Abigail, 2003, for comp.lang.perl.misc. + +This operator provides multi-line comments, by clever use +of heredoc syntax and beautiful symmetry. +Quoting C<< >>: + + <> + 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 ribbon with the C<;> throwing blade attached +to it. + +Note that the "commented" text is actually a double-quoted string in +void context, which can have some side effects. + +=head2 Screwdriver operators + +Discovered by Dmitry Karasik, 2007, while looking for C-based operators. + +All screwdriver operators are conditional operators. Like screwdrivers, +they come in 4 major types, with different handle lengths. + +=over 4 + +=item * + +Flathead + + -=!! + -=! + +This operator provides conditional decrement: + + $x -=!! $y # $x-- if $y; + $x -=! $y # $x-- unless $y; + +=item * + +Phillips + + +=!! + +=! + +This operator provides conditional increment: + + $x +=!! $y; # $x++ if $y; + $x +=! $y; # $x++ unless $y; + +=item * + +Torx + + *=!! + *=! + +This operator provides conditional reset to C<0>: + + $x *=!! $y; # $x = 0 unless $y; + $x *=! $y; # $x = 0 if $y; + +The torx screwdriver operator does not work properly with negative numbers +different from C<-1> on Perl versions lower than or equal to 5.13.5. +It also fails with C<-1> on Perl versions lower than or equal to 5.7.0. + +=item * + +Pozidriv + + x=!! + x=! + +This operator provides conditional reset to C<''>: + + $x x=!! $y; # $x = '' unless $y; + $x x=! $y; # $x = '' if $y; + +(This one was discovered by Philippe Bruhat in 2009, while preparing a +talk about the secret operators.) + +=back + +Mnemonic: the screwdriver's head is the best mnemonic (C<-> and C<+> +for increment and decrement, C<*> for the null number, C for the +null string). + + +=head2 Winking fat comma + + ,=> + +Discovered by Abigail, 2010. +(Alternate nickname: "grappling hook") + +Visually looks like a fat comma, but without the left-hand side behaviour. + +This operator is used to retain the documenting features of the fat comma, +while disabling the string interpretation of the word to its left. + + use constant APPLE => 1; + use constant CHERRY => 2; + use constant BANANA => 3; + + %hash = ( + APPLE ,=> "green", + CHERRY ,=> "red", + BANANA ,=> "yellow", + ); + +is equivalent to: + + %hash = ( 1, "green", 2, "red", 3, "yellow" ); + +Mnemonic: the comma C<,> is an off-switch for the fat comma's stringification. + +=head2 Enterprise + + ( )x!! + +Discovered by Aristotle on PerlMonks, 2006. +(Alternate nicknames: "NCC-1701", "snail") + +It is often necessary to conditionally include items in a list: + + my @shopping_list = ('bread', 'milk'); + push @shopping_list, 'apples' if $cupboard{apples} < 2; + push @shopping_list, 'bananas' if $cupboard{bananas} < 2; + push @shopping_list, 'cherries' if $cupboard{cherries} < 20; + push @shopping_list, 'tonic' if $cupboard{gin}; + +The Enterprise lets you build the list and add only the items that +match the condition, in a single statement: + + my @shopping_list = ( + 'bread', + 'milk', + ('apples' )x!! ( $cupboard{apples} < 2 ), + ('bananas' )x!! ( $cupboard{bananas} < 2 ), + ('cherries' )x!! ( $cupboard{cherries} < 20 ), + ('tonic' )x!! $cupboard{gin}, + ); + +This operator is a container, which means the Enterprise can have a +large crew. + +The Enterprise is simply a list repetition operator C<< ()x >> +followed by a boolean (see the L operator above) which will be +interpreted as 1 or 0 in a numeric context. +Note that the expression on the left is always evaluated, regardless of +the state of the condition. + +Because of precedence issues, complex conditions on the tail of the +Enterprise may need to be put between parentheses. + +=head2 Key to the truth + + 0+!! + +Discovered by Toby Inkster, 2013. + +This operator is a combination of the Venus and bang bang operators. +It simply makes the boolean false into the C<0> numeric value. + + my $true = 0+!! 'a string'; # now 1 + my $false = 0+!! undef; # now 0 + +=head2 Abbott and Costello + + ||() + +Discovered by Yves Orton. + +This operator makes a false value disappear in list context. +It simply replaces a false scalar by the empty list. + + my @shopping_list = ( + 'bread', + 'milk', + $this ||(), + $that ||(), + 'apples' + ); + +Mnemonic: one is tall (and also the "straight man") and one is fat, +just like the famous comedy duo. + +=head2 Leaning Abbott and Costello + + //() + +Proposed by Damien Krotkine, 2014. + +This operator works exactly like the L, except +that it only makes C disappear in list context. + +This operator only works in Perl versions above 5.10. + +Mnemonic: in this version, the "straight man" is leaning +(and so the associativity is really "(leaning Abbott) and Costello"). + +=head1 SECRET CONSTANTS + +=head2 Space fleet + + <=><=><=> + +Discovered by Damian Conway. + +Even though it looks like a sequence of three spaceship operators, +only the middle ship is an actual spaceship. The two outer "spaceships" +are actually calls to C. + +This constant has the value C<0>. + +=head2 Amphisbaena + + <~> + +Discovered by Rafaël Garcia-Suarez, 2009. + +Under Unix, will be equal to the real user home directory (by using C). +On Win32 it will expand to C<$ENV{HOME}> if it is set (which is quite uncommon) +or return C<'~'> else. + +=head1 AUTHOR + +Philippe Bruhat (BooK) + +=head1 ACKNOWLEDGMENTS + +The author would like to thank José Castro, Andrew Savige, Dmitry +Karasik, Abigail, Yitzchak Scott-Thoennes, Zefram, Tye McQueen, Maxim +Vuets, Aristotle Pagaltzis, Toby Inkster, Ævar Arnfjörð Bjarmason, +Rafaël Garcia-Suarez, Andreas J. König, Andy Armstrong, Pau Amma, +Keith C. Ivey, Michael R. Wolf, Olivier Mengué, Yves Orton, Damien Krotkine, +Diab Jerius, Ivan Bessarabov +and the Fun With Perl mailing list for inspiration, suggestions and patches. + +=head1 CONTRIBUTING + +If you know of other secret operators or constants, please let me know! + +However, before sending me your latest creation, be aware that, although +these are not set in stone, I consider the following criteria before +adding an operator or constant to this list: + +=over 4 + +=item * + +does it have a nickname? (usually one that matches its ASCII-art shape) + +=item * + +is it actually used in the wild? + +=item * + +does it have a golf-specific interest? (i.e. does it perform some useful +operation in significantly fewer characters than "normal" Perl code?) + +=item * + +does it have some historical interest? + +=back + +=head1 REFERENCES + +As shown below, most of the secret operator action happens +on the Fun With Perl mailing-list. + +=over 4 + +=item * + +Around 1993, according to Randal Schwartz in his "I" +talk given on July 25, 2013 at OSCON: + +IE operator for me (I named the E=E)> + +=item * + +Post C<< <1994May1.035104.25990@netlabs.com> >> in C + +Larry Wall discovers the baby cart and describes it as "a way to +interpolate function results into a string". + +=item * + +Post C<< >> in C + +Abigail coins the term "secret operator" to describe C<< <> m ; >>. + +=item * + +L + +Original "secret operators" thread. +Several of the detailed explanations in this manual page come from this thread. + +=item * + +L + +Description of the space station operator. + +=item * + +L + +Philippe Bruhat uses the word "venus" to describe C<0+>. + +=item * + +L + +Naming the baby cart operator. + +=item * + +L + +Aristotle Pagaltzis explains how the baby cart can be used to break aliasing. + +=item * + +L + +I, +by Aristotle Pagaltzis, describes the Enterprise operator. + +=item * + +L + +Description of the flaming X-Wing secret operator. + +=item * + +L + +Description of the screwdriver operators, and other C-based operators. + +=item * + +L + +Description of the fourth screwdriver operator (Pozidriv). + +=item * + +L + +Description of the sperm/kite operator. + +=item * + +L + +Proposal for an alternate, family-friendly, nickname for the goatse +operator, with a second order inside joke. + +=item * + +The Abbott and Costello operator was first presented to me on 2013-09-25 +by Yves Orton in private messages. + +I tried to propose "Laurel and Hardy" as a more internationally +understable alternative, but it turns out Hardy is I the fat and +the tall one. + +=item * + +The key to the truth operator was described to me on 2013-09-28 +by Toby Inkster on the C<#moose> IRC channel and private messages. + +=item * + +On 2014-02-18, on the C<#perlfr> IRC channel, Damien Krotkine notes that +he uses C more than C<||()>, to which Philippe Bruhat answers +immediately with the name "Leaning Abbot and Costello", noting that +Abbot is the tall one. + +=back + +More secret operators didn't make it to this list, because they +don't have a name yet. + +=over 4 + +=item * + +L + +The fwp post that presents the screwdriver operators also presents a +few more C-based operators. + +=back + +=head1 COPYRIGHT + +Copyright 2010-2014 Philippe Bruhat (BooK). + +=head1 LICENSE + +This documentation is free; you can redistribute it and/or modify it +under the same terms as Perl itself. + +=cut + From e8bfac563e99c560962b22cb2ea89b86e2ca0b54 Mon Sep 17 00:00:00 2001 From: Nikolay Mishin Date: Fri, 3 Oct 2014 10:49:41 +0400 Subject: [PATCH 02/28] Update perlsecret.ru.pod --- lib/perlsecret.ru.pod | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/lib/perlsecret.ru.pod b/lib/perlsecret.ru.pod index 7f8533f..9ca7f06 100644 --- a/lib/perlsecret.ru.pod +++ b/lib/perlsecret.ru.pod @@ -2,22 +2,22 @@ =head1 NAME -perlsecret - Perl secret operators and constants +perlsecret - Cекретный операторы и константы Perl -=head1 SYNOPSIS +=head1 КРАТКИЙ ОБЗОР -Perl secret operators: +Cекретный операторы Perl: - Operator Nickname Function + Оператор Кличка Функция ====================================================== - 0+ Venus numification - @{[ ]} Babycart list interpolation - !! Bang bang boolean conversion - }{ Eskimo greeting END block for one-liners - ~~ Inchworm scalar - ~- Inchworm on a stick high-precedence decrement - -~ Inchworm on a stick high-precedence increment - -+- Space station high-precedence numification + 0+ Венус Venus Приведение к цифре + @{[ ]} Детскаякаляска Babycart интерполяция списка + !! 2 удара Bang bang логическое преобразование + }{ Эскимосское приветствие КОНЕЦ блока для однострочного скрипта + ~~ Дюймовыйчервь Inchworm scalar + ~- Дюймовыйчервь на палке декремент высокого приоритета + -~ Дюймовыйчервь на палке декремент высокого приоритета + -+- Космическая станция Приведение к цифре высокого приоритета =( )= Goatse scalar / list context =< >=~ Flaming X-Wing match input, assign captures ~~<> Kite a single line of input From d38bfcb29e1806bb80ae8918288b49d4daea422e Mon Sep 17 00:00:00 2001 From: Nikolay Mishin Date: Fri, 3 Oct 2014 15:45:17 +0400 Subject: [PATCH 03/28] Update perlsecret.ru.pod --- lib/perlsecret.ru.pod | 42 +++++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/lib/perlsecret.ru.pod b/lib/perlsecret.ru.pod index 9ca7f06..dd2ebd0 100644 --- a/lib/perlsecret.ru.pod +++ b/lib/perlsecret.ru.pod @@ -14,32 +14,32 @@ Cекретный операторы Perl: @{[ ]} Детскаякаляска Babycart интерполяция списка !! 2 удара Bang bang логическое преобразование }{ Эскимосское приветствие КОНЕЦ блока для однострочного скрипта - ~~ Дюймовыйчервь Inchworm scalar + ~~ Дюймовыйчервь Inchworm скалярный ~- Дюймовыйчервь на палке декремент высокого приоритета -~ Дюймовыйчервь на палке декремент высокого приоритета -+- Космическая станция Приведение к цифре высокого приоритета - =( )= Goatse scalar / list context - =< >=~ Flaming X-Wing match input, assign captures - ~~<> Kite a single line of input - <> m ; Ornate double-bladed sword multiline comment - -=! -=!! Flathead conditional decrement - +=! +=!! Phillips conditional increment - x=! x=!! Pozidriv conditional reset to '' - *=! *=!! Torx conditional reset to 0 - ,=> Winking fat comma non-stringifying fat comma - ()x!! Enterprise boolean list squash - 0+!! Key to the truth numeric boolean conversion - ||() Abbott and Costello remove false scalar from list - //() Leaning Abbott and Costello remove undef from list - -Perl secret constants: - - Constant Nickname Value + =( )= Гоатсе скалярный / списочный контекст + =< >=~ Пылающий X-Wing Истребитель ищем во входных данных и присваиваем захваченное + ~~<> Кайт, девочка убийца Одиночная строка ввода + <> m ; Богатый двухлезвийный меч Многострочный комментарий + -=! -=!! Простак условное уменьшение + +=! +=!! Филипс условное увеличение + x=! x=!! Крестовая условный резет на '' + *=! *=!! Торкс Шестилучевая отвертка условный резет на 0 + ,=> Подмигивающая жирная запятая не стрингифицирующая жирная запятая + ()x!! Смелость Enterprise Сквош логического списка + 0+!! Ключ к истине числовое преобразование логических значений + ||() Эбботт и Костелло Комед дуэт удалить ложный скаляр из списка + //() Наклон Эбботта и Костелло удалить undef из списка + +Perl секретный константы: + + Константы Кличка (Nickname) Значение ====================================================== - <=><=><=> Space fleet 0 - <~> Amphisbaena $ENV{HOME} + <=><=><=> Космический флот 0 + <~> Амфисбена Двойной путь $ENV{HOME} -=head1 DESCRIPTION +=head1 ОПИСАНИЕ Perl has a long tradition of giving nicknames to some of its operators (possibly a form of Huffmanisation). These nicknames are based on the From abe1d439713b23f74e7961a248bc34f7a7e56b19 Mon Sep 17 00:00:00 2001 From: Nikolay Mishin Date: Tue, 7 Oct 2014 00:20:55 +0400 Subject: [PATCH 04/28] Update perlsecret.ru.pod --- lib/perlsecret.ru.pod | 34 +++++++++++++++++++++++----------- 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/lib/perlsecret.ru.pod b/lib/perlsecret.ru.pod index dd2ebd0..1de19e2 100644 --- a/lib/perlsecret.ru.pod +++ b/lib/perlsecret.ru.pod @@ -1,6 +1,6 @@ =encoding utf8 -=head1 NAME +=head1 НАИМЕНОВАНИЕ perlsecret - Cекретный операторы и константы Perl @@ -32,7 +32,7 @@ Cекретный операторы Perl: ||() Эбботт и Костелло Комед дуэт удалить ложный скаляр из списка //() Наклон Эбботта и Костелло удалить undef из списка -Perl секретный константы: +Perl секретные константы: Константы Кличка (Nickname) Значение ====================================================== @@ -41,15 +41,27 @@ Perl секретный константы: =head1 ОПИСАНИЕ -Perl has a long tradition of giving nicknames to some of its operators -(possibly a form of Huffmanisation). These nicknames are based on the -appearance of the operator, rather than its function. -The well-known examples -are the I (C<< <> >>), nicknamed by Geneva Wall -and the I (C<< <=> >>), nicknamed by Randal Schwartz. -Some lesser known Perl operators with a nickname are the I -(C<< => >>) and I (C<< ... >>). - +Perl имеет давнюю традицию давать прозвища для некоторых из своих операторов +(возможноя форма очеловечивания). Эти прозвища основаны на +скорее на виде оператора, чем на его функции. +Известные примеры I<бриллиантовый оператор> (C<< <> >>), +по прозвищу Стена Женевы и I<оператор космического корабля> (C<< <=> >>), +прозванный Рендаль Шварц. +Вот некоторые менее известные операторы Perl с ником I<толстая запятая> +(C<< => >>) и I<болтовня> (C<< ... >>). + +Perl «Я < секретный операторы настроек» были обнаружены (или созданы) +Perl обфускаторов и гольфисты, обычно при поиске более короткий путь к +Выполните данную операцию. +Секретный операторы не являются на самом деле секрет, и они не являются на самом деле +операторы либо. Perl анализатор специально не признать их, +и не пытается скрывать их от вас. +Но они, как операторы в том смысле, что эти программистов Perl см +их часто достаточно, чтобы признать их не думая о их меньше +Запчасти и в конечном итоге добавить их в их элементов. +И они, как секреты в том смысле, что они должны быть обнаружены +их будущего пользователя (или передаваться парень программист), потому что они +явно не описаны в документации основных Perl. The Perl "I" have been discovered (or created) by Perl obfuscators and golfers, usually when looking for a shorter way to perform a given operation. From 759dcb398a55cc281e1703c9034d3f7827ed6258 Mon Sep 17 00:00:00 2001 From: Nikolay Mishin Date: Tue, 7 Oct 2014 22:38:35 +0400 Subject: [PATCH 05/28] Update perlsecret.ru.pod --- lib/perlsecret.ru.pod | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/perlsecret.ru.pod b/lib/perlsecret.ru.pod index 1de19e2..a078d7c 100644 --- a/lib/perlsecret.ru.pod +++ b/lib/perlsecret.ru.pod @@ -50,11 +50,11 @@ Perl имеет давнюю традицию давать прозвища дл Вот некоторые менее известные операторы Perl с ником I<толстая запятая> (C<< => >>) и I<болтовня> (C<< ... >>). -Perl «Я < секретный операторы настроек» были обнаружены (или созданы) -Perl обфускаторов и гольфисты, обычно при поиске более короткий путь к -Выполните данную операцию. -Секретный операторы не являются на самом деле секрет, и они не являются на самом деле -операторы либо. Perl анализатор специально не признать их, +"I" Perl были обнаружены (или созданы) +Perl обфускаторами и Perl гольфистами, обычно при поиске более короткого пути +выполнения данной операции. +Секретный операторы не являются на самом деле секретными, и они не являются на самом деле +операторами.Perl анализатор специально не признает их, и не пытается скрывать их от вас. Но они, как операторы в том смысле, что эти программистов Perl см их часто достаточно, чтобы признать их не думая о их меньше From e08967a2c5592f912e95d59dcd258ed32f72c518 Mon Sep 17 00:00:00 2001 From: Nikolay Mishin Date: Wed, 8 Oct 2014 16:29:24 +0400 Subject: [PATCH 06/28] Update perlsecret.ru.pod --- lib/perlsecret.ru.pod | 101 +++++++++++++++++++----------------------- 1 file changed, 45 insertions(+), 56 deletions(-) diff --git a/lib/perlsecret.ru.pod b/lib/perlsecret.ru.pod index a078d7c..6aa9639 100644 --- a/lib/perlsecret.ru.pod +++ b/lib/perlsecret.ru.pod @@ -52,61 +52,50 @@ Perl имеет давнюю традицию давать прозвища дл "I" Perl были обнаружены (или созданы) Perl обфускаторами и Perl гольфистами, обычно при поиске более короткого пути -выполнения данной операции. +выполнения операции. Секретный операторы не являются на самом деле секретными, и они не являются на самом деле -операторами.Perl анализатор специально не признает их, +операторами. Perl анализатор специально не признает их, и не пытается скрывать их от вас. -Но они, как операторы в том смысле, что эти программистов Perl см -их часто достаточно, чтобы признать их не думая о их меньше -Запчасти и в конечном итоге добавить их в их элементов. -И они, как секреты в том смысле, что они должны быть обнаружены -их будущего пользователя (или передаваться парень программист), потому что они -явно не описаны в документации основных Perl. -The Perl "I" have been discovered (or created) by -Perl obfuscators and golfers, usually when looking for a shorter way to -perform a given operation. -Secret operators are not actually secret, and they are not actually -operators either. The perl parser does not specifically recognise them, -and no one is trying to hide them from you. -But they are like operators in the sense that these Perl programmers see -them often enough to recognize them without thinking about their smaller -parts, and eventually add them to their toolbox. -And they are like secrets in the sense that they have to be discovered by -their future user (or be transmitted by a fellow programmer), because they -are not explicitly described in the Perl core documentation. - -Because secret operators are not operators they don't have real names, and -so they need nicknames. -Like the above Perl operators, their name is usually related to their shape. - -The term "secret operator" was probably coined by Abigail in a -C post in January 2003. - -=head2 A word of warning - -Many of those "operators" are not suitable for production code, -because they are obscure to the uninitiated, although some are just names -for common idioms. The really secret operators are used by golfers, -obfuscators and people who like -to have fun with their favorite programming language. - -You're welcome to try these at home, but they might not be safe for work! - -=head1 SECRET OPERATORS - -The following section presents the Perl secret operators, with -some historical context, an explanation of how they work and -examples of use. - -=head2 Venus +Но они, являются операторами в том смысле, Perl программистам достаточно посмотреть + на их конструкцию, чтобы понять, что они делают, не задумываясь о более мелких элементах + и в конечном итоге добавляют их в свою коллецию инструментов. +Они являются секретами в том смысле, что они должны обнаружены +их будущем пользоватем (программистом), потому что они +явно не описаны в основной документации Perl. + +Так как секретные операторы не являются операторами, они не имеют реальных имен, и +поэтому они нуждаются в прозвища (никнеймах). +Как видно из описания Perl операторов выше их имя обычно связано с их формой. + +Термин "секретный оператор", вероятно, был придуман Абигейлом в + сообщении на C в январе 2003 года. + +=head2 Слово предупреждения + +Многие из этих "операторов", не подходят для производственного кода, +потому что они являются неясными для непосвященных, хотя некоторые из них - это просто имена +для общих идиом (словосочетаний, фр. idiome «язык, наречие» происх от др.-греч. ἰδίωμα «особенность, своеобразие). +Реально секретные операторы используются гольфистами, +обфускаторами и людьми, которые любят + повеселиться с их любимым языком программирования. + +Вы можете попробовать их дома, но они могут быть не безопасны для работы! + +=head1 СЕКРЕТНЫЕ ОПЕРАТОРЫ + +В следующем разделе представлены секретные операторы Perl с +некоторым историческим контекстом, объяснением того, как они работают и +примерами использования. + +=head2 Венера(Venus) 0+ +0 -The I operator is a name given to a very common idiom. It performs -the numification of the value on its -right/left, depending of the version used. (This is accomplished by -using the identity element for the addition). +Оператор I<Венера> - это очень распространенный фразеологизм. Он выполняет +превращение в цифру, нумификацию значения стоящего справа/слева +в зависимости от используемых версий. (Это достигается путем +использование идентификатора добавления I<+>). print 0+ '23a'; # 23 @@ -124,18 +113,18 @@ using the identity element for the addition). print 0+ $!, ' ', $!; # 2 No such file or directory -Note that C<0+> is the method name used for "numeric conversion" by -the C module. +Обратите внимание, что C<0+> — это имя метода, для "числового преобразования" + в модуле C. -=head2 Baby cart +=head2 Детская коляска (Baby cart) @{[ ]} -Discovered by Larry Wall, 1994. -(Alternate nicknames: "shopping-trolley", "pram", "turtle") +Открыта Лари Воллом, 1994. +(Альтернативные клички: "шоппинг троллей", "коляска", "черепаха") -The I operator performs list interpolation inside a string. -The list items are separated by the value of C<$">. +Оператор I<Детская коляска> выполняет интерполяцию список внутри строки. +Элементы списка разделяются значением C<$">. # SQL in a heredoc local $" = ','; From 149cb9451e2daf2b5f40238b6d8af89357747a45 Mon Sep 17 00:00:00 2001 From: Nikolay Mishin Date: Fri, 10 Oct 2014 09:58:27 +0400 Subject: [PATCH 07/28] Update perlsecret.ru.pod --- lib/perlsecret.ru.pod | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/lib/perlsecret.ru.pod b/lib/perlsecret.ru.pod index 6aa9639..24879fa 100644 --- a/lib/perlsecret.ru.pod +++ b/lib/perlsecret.ru.pod @@ -123,10 +123,10 @@ Perl обфускаторами и Perl гольфистами, обычно п Открыта Лари Воллом, 1994. (Альтернативные клички: "шоппинг троллей", "коляска", "черепаха") -Оператор I<Детская коляска> выполняет интерполяцию список внутри строки. +Оператор I<Детская коляска> выполняет интерполяцию списка внутри строки. Элементы списка разделяются значением C<$">. - # SQL in a heredoc + # SQL в heredoc (документ-здесь) local $" = ','; my $sth = $self->execute( << "SQL" ); SELECT id, name, salary @@ -134,17 +134,17 @@ Perl обфускаторами и Perl гольфистами, обычно п WHERE id IN (@{[ keys %employee ]}) SQL - # process args in %arg - # and spit out the unknown ones + # аргументы находятся в хэше %arg + # и выводятся неизвестные аргументы die "Uuh?: @{[ sort keys %arg ]}\n" -Another use case is for breaking aliasing (i.e. make a copy); for example -to avoid the C fatal error -when running such code: +Еще один вариант использования – для взлома алиасов (т.е. создании копии); Например, +чтобы избежать фатальной ошибки при C<попытке модификации значения только для чтения> +при выполнении следующего кода: for (qw( 1 2 3 )) { - $_ = $_ * $_; # contrived - print "square: $_\n"; + $_ = $_ * $_; # надуманный + print "площадь: $_\n"; } With the babycart, the topic is an actually modifiable copied scalar. From 9a291339b897a7fc7534a303ecf8a8175b86510f Mon Sep 17 00:00:00 2001 From: Nikolay Mishin Date: Fri, 10 Oct 2014 14:18:52 +0400 Subject: [PATCH 08/28] Update perlsecret.ru.pod --- lib/perlsecret.ru.pod | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/lib/perlsecret.ru.pod b/lib/perlsecret.ru.pod index 24879fa..dbb12ed 100644 --- a/lib/perlsecret.ru.pod +++ b/lib/perlsecret.ru.pod @@ -147,20 +147,20 @@ Perl обфускаторами и Perl гольфистами, обычно п print "площадь: $_\n"; } -With the babycart, the topic is an actually modifiable copied scalar. +С детской коляской (babycart) изменяемые данные фактически копируются в скаляр. for ( @{[ qw( 1 2 3 ) ]} ) { - $_ = $_ * $_; # contrived - print "square: $_\n"; + $_ = $_ * $_; # надуманный + print "площадь: $_\n"; } -This is a I, or I operator. The expression -inside the C<[]> is run in list context, stored in an anonymous array, -which is immediately dereferenced by C<@{}>. +Это I<контейнер>, или I<окаймляющий> (I<циркупфикс>) operator. Выражение внутри +C<[]> выполняетс в списочном контексте и сохраняется в анонимном массиве, +который сразу разыменовывается с помощью C<@{}>. -You will see this occasionally in production code. +Вы это иногда увидите в рабочем коде. -=head2 Bang bang +=head2 2 удара Bang bang !! From c6ef34aaa8234b3413fd8faeb553d324b97f256b Mon Sep 17 00:00:00 2001 From: Nikolay Mishin Date: Sat, 11 Oct 2014 00:10:34 +0400 Subject: [PATCH 09/28] Update perlsecret.ru.pod --- lib/perlsecret.ru.pod | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/lib/perlsecret.ru.pod b/lib/perlsecret.ru.pod index dbb12ed..ddbe5cd 100644 --- a/lib/perlsecret.ru.pod +++ b/lib/perlsecret.ru.pod @@ -154,39 +154,39 @@ Perl обфускаторами и Perl гольфистами, обычно п print "площадь: $_\n"; } -Это I<контейнер>, или I<окаймляющий> (I<циркупфикс>) operator. Выражение внутри -C<[]> выполняетс в списочном контексте и сохраняется в анонимном массиве, +Это I<контейнер>, или I<окаймляющий> (I<циркумфикс>) operator. Выражение внутри +C<[]> выполняется в списочном контексте и сохраняется в анонимном массиве, который сразу разыменовывается с помощью C<@{}>. -Вы это иногда увидите в рабочем коде. +Вы это иногда увидите это в рабочем коде. =head2 2 удара Bang bang !! -This operator was in common usage by C programmers even before Perl existed. -It performs boolean conversion, by performing logical negation -twice. +Этот оператор был в общем использовании программистами C даже до существования Perl. +Он выполняет логическое преобразование, выполняя логическое отрицание +дважды. - my $true = !! 'a string'; # now 1 - my $false = !! undef; # now '' + my $true = !! 'a string'; # теперь 1 + my $false = !! undef; # теперь '' -=head2 Eskimo greeting +=head2 Приветствие Эскимосов (Eskimo greeting0 }{ -(Alternate nickname: "butterfly") +(Альтернативный ник: "бабочка") -Discovered by Abigail, in 1997. +Открыт Абигалем в 1997. -The I operator is an C block for one-liners. +Оператор I<приветствие Эскимосов> является блоком C для однострочников. -The following program counts and prints the number of lines in the input: +Следующая программа подсчитывает и выводит число строк во входных данных: $ perl -lne '}{print$.' -The Eskimo greeting abuses the way the B<-p> and B<-n> options generate -Perl code (as shown by using the C module): +Приветствие Эскимосов злоупотребляет использование опций B<-p> и B<-n> генерируя +Perl код (показано, используя модуль C): $ perl -MO=Deparse -lne '}{print$.' -e syntax OK From ac9471e48d4654792d83a4871e0f2157f9a51e04 Mon Sep 17 00:00:00 2001 From: Nikolay Mishin Date: Mon, 13 Oct 2014 17:55:14 +0400 Subject: [PATCH 10/28] Update perlsecret.ru.pod --- lib/perlsecret.ru.pod | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/lib/perlsecret.ru.pod b/lib/perlsecret.ru.pod index ddbe5cd..2878513 100644 --- a/lib/perlsecret.ru.pod +++ b/lib/perlsecret.ru.pod @@ -198,18 +198,17 @@ Perl код (показано, используя модуль C): print $.; } -The discovery was done after The Perl Journal published an interview with -Chip Salzenberg, in which he explained what hack perl uses to implement -C<< -p >> and C<< -n >>. - -Ethnographic note: in modern Western culture, an eskimo kiss is the act -of pressing the tip of one's nose against another's. It is loosely based -on a traditional Inuit greeting called a I, that early explorers -of the Arctic dubbed "Eskimo kissing" when they first witnessed it. The -kunik itself is not a kiss, not erotic, and simply of form of affectionate -greeting. - -=head2 Inchworm +Открытие было сделано после того, как Perl Journal опубликовал интервью с +Чипом Сальзенбергом(Chip Salzenberg), в котором он объяснил, что хак perl использует для реализации +C<< -p >> и C<< -n >>. + +Этнографическое примечание: в современной Западной культуре эскимосский поцелуй - это +, когда люди целуются друг с другом соприкасая носы. Это основывается +на традиционном инуитском приветствии, названном I<куник>, ранние исследователи +Арктики назвали его "эскимосский поцелуй" ("Eskimo kissing"), когда они впервые увидели его. +Сам куник не поцелуй, не эротичный, и просто форма нежного приветствия. + +=head2 Дюймовый_червь (Inchworm) ~~ From a1faf80da00f8a6dfbc359c64c26112a9e02dbe1 Mon Sep 17 00:00:00 2001 From: Nikolay Mishin Date: Tue, 14 Oct 2014 10:36:51 +0400 Subject: [PATCH 11/28] Update perlsecret.ru.pod --- lib/perlsecret.ru.pod | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/lib/perlsecret.ru.pod b/lib/perlsecret.ru.pod index 2878513..41f6d64 100644 --- a/lib/perlsecret.ru.pod +++ b/lib/perlsecret.ru.pod @@ -171,7 +171,7 @@ C<[]> выполняется в списочном контексте и сох my $true = !! 'a string'; # теперь 1 my $false = !! undef; # теперь '' -=head2 Приветствие Эскимосов (Eskimo greeting0 +=head2 Приветствие Эскимосов (Eskimo greeting) }{ @@ -212,16 +212,22 @@ C<< -p >> и C<< -n >>. ~~ -This operator is basically a shorter C (shaves 4 characters!) -using the same idea as the secret bang bang operator. +Этот оператор в основном короче C(убирает целых 4 символа!) +используя ту же идею, как секретный оператор bang bang. $ perl -Esay~~localtime Tue Mar 13 19:53:25 2012 -The inchworm looks very much like the smart-match operator introduced -in Perl 5.10, but since it's actually a sequence of two unary operators, -the Perl parser can't mix it up with the binary smart-match. +Дюймочервь выглядит очень похоже на смарт матч оператор, представленный +в Perl 5.10, но так как это на самом деле последовательность двух унарных операторов, +анализатор Perl не сможет смешать его с двоичным смарт матчем. +Обратите внимание, что Perl C<~> операнд чувствительных: если его операнд имеет числовой +значение (либо потому, что он был присвоен номер, в результате числовое +операция, или используется в числовом контексте), это побитовое числовой +отрицание (сначала неявно преобразует целое число без знака (УФ), или менее +область C < использования L настроек, знаковое целое число, (IV)); в противном случае это +Строка поразрядное отрицание. Note that Perl's C<~> is operand sensitive: if its operand has a numeric value (either because it was assigned a number, the result of a numeric operation, or had been used in numeric context), it is a numeric bitwise From 510c933b6d8e7b2064d31f5f2065b3a269b1f1a8 Mon Sep 17 00:00:00 2001 From: Nikolay Mishin Date: Tue, 14 Oct 2014 10:37:06 +0400 Subject: [PATCH 12/28] Update perlsecret.ru.pod --- lib/perlsecret.ru.pod | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/perlsecret.ru.pod b/lib/perlsecret.ru.pod index 41f6d64..74eb156 100644 --- a/lib/perlsecret.ru.pod +++ b/lib/perlsecret.ru.pod @@ -2,7 +2,7 @@ =head1 НАИМЕНОВАНИЕ -perlsecret - Cекретный операторы и константы Perl +perlsecret - Cекретные операторы и константы Perl =head1 КРАТКИЙ ОБЗОР From 4375e338ad78eea780cf1ff46c7457fb53a2096a Mon Sep 17 00:00:00 2001 From: Nikolay Mishin Date: Tue, 14 Oct 2014 11:16:36 +0400 Subject: [PATCH 13/28] Update perlsecret.ru.pod --- lib/perlsecret.ru.pod | 43 ++++++++++++++++++------------------------- 1 file changed, 18 insertions(+), 25 deletions(-) diff --git a/lib/perlsecret.ru.pod b/lib/perlsecret.ru.pod index 74eb156..3c0dced 100644 --- a/lib/perlsecret.ru.pod +++ b/lib/perlsecret.ru.pod @@ -206,7 +206,7 @@ C<< -p >> и C<< -n >>. , когда люди целуются друг с другом соприкасая носы. Это основывается на традиционном инуитском приветствии, названном I<куник>, ранние исследователи Арктики назвали его "эскимосский поцелуй" ("Eskimo kissing"), когда они впервые увидели его. -Сам куник не поцелуй, не эротичный, и просто форма нежного приветствия. +Сам куник не является поцелелуем, он не эротичен, это просто форма нежного приветствия. =head2 Дюймовый_червь (Inchworm) @@ -222,36 +222,29 @@ C<< -p >> и C<< -n >>. в Perl 5.10, но так как это на самом деле последовательность двух унарных операторов, анализатор Perl не сможет смешать его с двоичным смарт матчем. -Обратите внимание, что Perl C<~> операнд чувствительных: если его операнд имеет числовой -значение (либо потому, что он был присвоен номер, в результате числовое -операция, или используется в числовом контексте), это побитовое числовой -отрицание (сначала неявно преобразует целое число без знака (УФ), или менее -область C < использования L настроек, знаковое целое число, (IV)); в противном случае это -Строка поразрядное отрицание. -Note that Perl's C<~> is operand sensitive: if its operand has a numeric -value (either because it was assigned a number, the result of a numeric -operation, or had been used in numeric context), it is a numeric bitwise -negation (first implicitly converting to unsigned integer (UV), or under -the scope of C>, signed integer (IV)); otherwise it is a -string bitwise negation. +Обратите внимание, что Perl C<~> является чувствительным операндом: если его операнд имеет числовое +значение (либо потому, что был присвоен номер, в результате числовая +операция, или используется в числовом контексте), это побитовое числовое +отрицание (сначала неявно преобразует целое число без знака (unsigned integer (UV)), или +за областью C>, знаковое целое число, (signed integer (IV))); в противном случае это +строковое поразрядное(побитовое) отрицание. -And this explains how it differs from C. Instead of forcing the operand -into some kind of boolean, it forces it into some kind of either string or -number (depending on the operand). +И это объясняет, как эта операция отличается от C. Вместо того, чтобы заставить операнд + быть булевым (логическим), он применяет его или к строке или к цифре(в зависимости от операндов). -Thus, for most inputs, the inchworm acts just like C. +Таким образом, для большинства входных данных, Дюймочервь (inchworm) действует так же, как C. -Examples of exceptions: +Примеры исключений: - # floating point + # с плавающей точкой $x = 1.23; print ~~$x; # 1 - # string used in numeric context + # строка используется в числовом контексте $x = "1.23"; print ~~$x if $x != 0; # 1 - # integer out of range + # целое число вне диапазона (out of range) use Config '%Config'; $x = 2**( 8 * $Config{uvsize} ); @@ -272,20 +265,20 @@ Examples of exceptions: print ~~$x; # IV_MIN } -But it is also handy as a shorthand to get stringification from objects that -overload it in some useful way: +Но это также удобно, как собирательное для получения строки из объектов, +перегрузите его некоторым полезным образом: use DateTime; use JSON; my $now = DateTime->now; print encode_json { time => ~~$now }; -=head2 Inchworm on a stick +=head2 Дюймочервь на палке (Inchworm on a stick) ~- -~ -Discovered by Ton Hospel, 2002. +Открыт Томом Хоспелом, 2002. These two operators perform a high-precedence decrement (C<~->) and high-precedence increment (C<-~>) on integers (on a two's-complement From fa910a845e4e362475c1d43cf7ae5dc864e44541 Mon Sep 17 00:00:00 2001 From: Nikolay Mishin Date: Wed, 15 Oct 2014 11:01:48 +0400 Subject: [PATCH 14/28] Update perlsecret.ru.pod --- lib/perlsecret.ru.pod | 72 +++++++++++++++++++++---------------------- 1 file changed, 36 insertions(+), 36 deletions(-) diff --git a/lib/perlsecret.ru.pod b/lib/perlsecret.ru.pod index 3c0dced..ea1968d 100644 --- a/lib/perlsecret.ru.pod +++ b/lib/perlsecret.ru.pod @@ -280,47 +280,49 @@ C<< -p >> и C<< -n >>. Открыт Томом Хоспелом, 2002. -These two operators perform a high-precedence decrement (C<~->) and -high-precedence increment (C<-~>) on integers (on a two's-complement -architecture). It's a trick that assembly language programmers have -been using for decades. - -In C, Python and Ruby, they work on all integers. Due to how C<~> -is implemented in Perl (a little known fact is that Perl's bitwise -operators cast operands to unsigned integers without C> -and to signed integers with C), this pair of -secret operators is limited to signed integers. -It's actually even more limited by default: C<~-> only decrements integers -greater than 0, and C<-~> only increments integers lesser than 0. To -get the inchworms on a stick to work on all signed integers, they must be used -under the scope of C, so that signed integers are used everywhere in -bitwise operations. - -This golfing technique allows to get rid of a pair of parentheses: - - $y = ~-$x * 4; # identical to $y = ($x-1)*4; - - -Here's the proof: +Эти два оператора выполняют высокоприоритетный декремент (C<~->) и + высокоприоритетный инкремент(C<-~>) для целых чисел (на архитектуре +дополнительного кода ( two-complement) +https://ru.wikipedia.org/wiki/Дополнительный_код_(представление_числа)). +Этот трюк программисты языка ассемблера использую на протяжении десятилетий. + +В C, Python и Ruby они работают на всех целых числах. Из-за того, как оператор C<~> +реализован в Perl (мало известный факт, что побитовые +операторы Perl приводят операнд к беззнаковому целому ( unsigned integers) + без C> и к знаковому целому (signed integers) + с C), эта пара +секретных операторов ограничивается целыми числами со знаком. +Это на самом деле еще большее ограничение, по умолчанию: C<~-> только уменьшает целые числа +больше 0 и C<-~> только увеличивающем целые числа меньше 0. Для того, чтобы +Дюймочервь на палке (Inchworm on a stick) + работал на всех целых числах, он должен быть использован +в сфере C, таким образом знаковые целые(signed integers) + используются повсеместно в битовых операциях. + +Этот гольф методика позволяет избавиться от пары скобок: + + $y = ~-$x * 4; # аналогично $y = ($x-1)*4; + +Вот доказательство: $x - 1 == - ( -$x ) - 1 -In two's complement architectures, to get the opposite of a number, -all you need to do is flip all bits, and add 1. I.e., +В двудополнительной архитектуре, чтобы получить обратное числа, +все, что вам нужно сделать это сделать инверсию (flip) всех битов и добавить 1. То есть, -$i == ~$i + 1 -Using this to replace C< - ( -$x ) > in the above identity, we get: +Используем это, чтобы заменить C< - ( -$x ) > на показанное выше, мы получаем: $x - 1 == ( ~-$x + 1 ) - 1 -And after eliminating the ones from the equation, +И после устранения единиц из уравнения, $x - 1 == ~-$x -QED. +ЧТО И ТРЕБОВАЛОСЬ ДОКАЗАТЬ. (QED - от лат. quod erat demonstrandum) -For C<-~>, the proof is similar: +Для C<-~>, доказательство аналогично: $x + 1 == - ( -$x ) + 1 @@ -330,16 +332,14 @@ For C<-~>, the proof is similar: $x + 1 == -~$x +В обеих версиях высокий приоритет исходит из того, что C<~> +и унарный C<-> оба имеют более высокий приоритет, чем все другие арифметические +операторы (за исключением C<**>). -In both versions, the high precedence comes from the fact that C<~> -and unary C<-> both have higher precedence than all other arithmetic -operators (except C<**>). - -Mnemonic: the backwards-facing inchworm on a stick (C<~->) decrements, -and the forward-facing inchworm on a stick (C<-~>) increments. - +Мнемосхема: назад стоящий дюймочервь на палке(C<~->) уменьшает, +а дюймочервь по ходу движения на палке (C<-~>) приращяет. -=head2 Space station +=head2 Космическая станция (Space station) -+- From 0f9a354898b804339a3e8fa1fc566b3aee5bc90d Mon Sep 17 00:00:00 2001 From: Nikolay Mishin Date: Fri, 17 Oct 2014 09:42:22 +0400 Subject: [PATCH 15/28] Update perlsecret.ru.pod --- lib/perlsecret.ru.pod | 43 +++++++++++++++++++++---------------------- 1 file changed, 21 insertions(+), 22 deletions(-) diff --git a/lib/perlsecret.ru.pod b/lib/perlsecret.ru.pod index ea1968d..b6d711b 100644 --- a/lib/perlsecret.ru.pod +++ b/lib/perlsecret.ru.pod @@ -343,9 +343,9 @@ https://ru.wikipedia.org/wiki/Дополнительный_код_(предст -+- -Discovered by Alistair McGlinchy, 2005. +Открыт Алистером Макглинчи, 2005. -This operator performs a high precedence numification. +Этот оператор выполняет приведение к цифре с высоким приоритетом. print -+- '23a'; # 23 @@ -358,46 +358,45 @@ This operator performs a high precedence numification. $ref = []; print -+- $ref, ' ', "$ref"; # 151097816 ARRAY(0x90191d8) - print -+- $!, ' ', $!; # 2 No such file or directory + print -+- $!, ' ', $!; # 2 Нет такого файла или каталога -At first, this looks exactly like the Venus operator. However, because -the Venus operator uses a binary C<+>, it has a lower precedence than -the multiplicative operators like C<*> or C. On the other hand, -the space station operator is the concatenation of three unary operators, -and therefore has higher precedence. +Во-первых это выглядит точно как оператор Венеры. Однако, потому что +оператор Венеры использует двоичный C<+>, он имеет более низкий приоритет, чем +операторы умножения, такие как как C<*> или C.С другой стороны +оператор космической станции является объединением трех унарных операторов, +и поэтому имеет более высокий приоритет. -In the following example, we'll try to print the numification of -the string C<'20GBP'> (i.e. C<'20'>) repeated three times. +В следующем примере мы будем пытаться печатать приведнную к цифре строку + C<'20GBP'> (т.eе C<'20'>) повторенную 3 раза. - # wrong: prints the numification of '20GBP20GBP20GBP' + # неправильно: выведет нумификацию '20GBP20GBP20GBP' print 0+ '20GBP' x 3; # 20 - # wrong: does the equivalent of ( print '20' ) x 3 + # неправильно: это эквивалентно ( print '20' ) x 3 print( 0+ '20GBP' ) x 3; # 20 - # right: but too lengthy, too lispy + # правильно: но слишком длинно, слишком полисповски print( ( 0 + '20GBP' ) x 3 ); # 202020 - # right: uses the space station operator + # верно: использование оператора космическая станция (space station) print -+- '20GBP' x 3; # 202020 -However, because unary minus simply replace the initial C<-> or C<+> of a string -by its counterpart, the space station does B numify I -or I: +Тем не менее, т.к. унарный минус просто заменяеть начальный C <-> или C <+> строки +их аналогом, космическая станция B<не> переводит в цифры I<строки, начинающиеся с минуса> +или I <строки, которые не начинаются с числа>: print -+- 'two cents'; # +two cents print -+- '-2B' x 5; # -2B-2B-2B-2B-2B -In the above example, C<-+- '-2B'> produces the string C<'-2B'>, -whereas C<0+ '-2B'> would have given the expected number (C<-2>). +В примере выше, C<-+- '-2B'> производит строку C<'-2B'>, +в то время как C<0+ '-2B'> дал бы ожидаемое число (C<-2>). - -=head2 Goatse +=head2 Гоатсе, Коза (Goatse) =( )= -(Alternate nickname: "Saturn") +(Еще одно имя: "Сатурн") If you don't understand the name of this operator, consider yourself lucky. You are advised B to search the Internet for a visual explanation. From a074566713f040b56d8045fd86d5840f74252656 Mon Sep 17 00:00:00 2001 From: Nikolay Mishin Date: Fri, 17 Oct 2014 11:52:51 +0400 Subject: [PATCH 16/28] Update perlsecret.ru.pod --- lib/perlsecret.ru.pod | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/perlsecret.ru.pod b/lib/perlsecret.ru.pod index b6d711b..eaa3ea5 100644 --- a/lib/perlsecret.ru.pod +++ b/lib/perlsecret.ru.pod @@ -29,7 +29,7 @@ Cекретный операторы Perl: ,=> Подмигивающая жирная запятая не стрингифицирующая жирная запятая ()x!! Смелость Enterprise Сквош логического списка 0+!! Ключ к истине числовое преобразование логических значений - ||() Эбботт и Костелло Комед дуэт удалить ложный скаляр из списка + ||() Эбботт и Костелло Камеди дуэт удалить ложный скаляр из списка //() Наклон Эбботта и Костелло удалить undef из списка Perl секретные константы: From 7c58f539dc2883e7c8aea1912076bcbd586a277b Mon Sep 17 00:00:00 2001 From: Nikolay Mishin Date: Sat, 18 Oct 2014 23:30:28 +0400 Subject: [PATCH 17/28] Update perlsecret.ru.pod --- lib/perlsecret.ru.pod | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/lib/perlsecret.ru.pod b/lib/perlsecret.ru.pod index eaa3ea5..7389f97 100644 --- a/lib/perlsecret.ru.pod +++ b/lib/perlsecret.ru.pod @@ -398,21 +398,21 @@ https://ru.wikipedia.org/wiki/Дополнительный_код_(предст (Еще одно имя: "Сатурн") -If you don't understand the name of this operator, consider yourself lucky. -You are advised B to search the Internet for a visual explanation. +Если вы не понимаете имя этого оператора, считайте себя счастливчиком. +Вам рекомендуется B<не> искать его в Интернете для визуального объяснения. -The goatse operator provides a list context to its right side and -returns the number of elements to its left side. -Note that the left side must provide a scalar context; obviously, a list -context on the left side will receive the empty list in the middle. +Оператор гоатсе предоставляет списочный контекст его правую сторону и +возвращает количество элементов на ее левой стороне. +Обратите внимание, что левая сторона должна обеспечивать скалярный контекст; очевидно списочный +контекст с левой стороны будут получать пустой список в середине. -The explanation is that a list assignment in scalar context returns the -number of elements on the right-hand side of the assignment, no matter -how many of those elements were actually assigned to variables. In this -case, all the elements on the right are simply assigned to an empty list -(and therefore discarded). +Объяснение того, что присвоение списка в скалярном контексте возвращает +количество элементов в правой части назначения, независимо от +как много из этих элементов были на самом деле присваивоены переменным. В этом +случае все элементы справа просто передают пустой список +(и поэтому отбрасываются). - # count the words in $_ + # считает число слов в $_ $n =()= /word1|word2|word3/g; # $n = 1 @@ -421,6 +421,8 @@ case, all the elements on the right are simply assigned to an empty list # $n = 4 $n =()= "abababab" =~ /a/g; +Оператор goatse представляет собой контейнер (sic), поэтому он также может использоваться для +присвойте значения с правой стороны переменных внутри него. The goatse operator is a container (sic), so it can also be used to assign values from the right-hand side to the variables inside it. From e26758894814e540e6997b801261dc7e2e2f5139 Mon Sep 17 00:00:00 2001 From: Nikolay Mishin Date: Sat, 18 Oct 2014 23:56:19 +0400 Subject: [PATCH 18/28] Update perlsecret.ru.pod --- lib/perlsecret.ru.pod | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/lib/perlsecret.ru.pod b/lib/perlsecret.ru.pod index 7389f97..0b1594b 100644 --- a/lib/perlsecret.ru.pod +++ b/lib/perlsecret.ru.pod @@ -421,10 +421,8 @@ https://ru.wikipedia.org/wiki/Дополнительный_код_(предст # $n = 4 $n =()= "abababab" =~ /a/g; -Оператор goatse представляет собой контейнер (sic), поэтому он также может использоваться для -присвойте значения с правой стороны переменных внутри него. -The goatse operator is a container (sic), so it can also be used to -assign values from the right-hand side to the variables inside it. +Оператор гоатсе представляет собой контейнер (sic!), поэтому он также может использоваться для +присвоения значения с правой стороны переменным внутри него. # $n = 4; $b = 'a' $n =($b)= "abababab" =~ /a/g; @@ -432,6 +430,12 @@ assign values from the right-hand side to the variables inside it. # $n = 4; @c = qw( a a a a ) $n =(@c)= "abababab" =~ /a/g; +В некоторых случаях полный гоатсе не нужкн, потому что нет необходимости +для хранения значения в переменной. Побочный эффект списочного присвоения в +скалярные контексте можеь быть получен с я < правостороннюю goaste настроек (C < => ()) +используется в скалярных контексте некоторых других значит чем assignement +к скалярным значением. +Например: In some cases, the full goaste is not needed, because there is no need to store the value in a variable. The side-effect of list assignment in scalar context can be obtained with a I (C<()=>) From 2ab4e26e1f0716fc48e4fe199d47675935fbbcdf Mon Sep 17 00:00:00 2001 From: Nikolay Mishin Date: Sat, 18 Oct 2014 23:59:01 +0400 Subject: [PATCH 19/28] Update perlsecret.ru.pod --- lib/perlsecret.ru.pod | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/perlsecret.ru.pod b/lib/perlsecret.ru.pod index 0b1594b..8f0c781 100644 --- a/lib/perlsecret.ru.pod +++ b/lib/perlsecret.ru.pod @@ -430,9 +430,9 @@ https://ru.wikipedia.org/wiki/Дополнительный_код_(предст # $n = 4; @c = qw( a a a a ) $n =(@c)= "abababab" =~ /a/g; -В некоторых случаях полный гоатсе не нужкн, потому что нет необходимости +В некоторых случаях полный гоатсе не нужен, потому что нет необходимости для хранения значения в переменной. Побочный эффект списочного присвоения в -скалярные контексте можеь быть получен с я < правостороннюю goaste настроек (C < => ()) +скалярные контексте может быть получен I<правостороннем гоатсе> (C<()=>) используется в скалярных контексте некоторых других значит чем assignement к скалярным значением. Например: From be13cf682e9469156de98741b3ff6e625b616d9b Mon Sep 17 00:00:00 2001 From: Nikolay Mishin Date: Sun, 19 Oct 2014 00:12:38 +0400 Subject: [PATCH 20/28] Update perlsecret.ru.pod --- lib/perlsecret.ru.pod | 33 ++++++++++++++------------------- 1 file changed, 14 insertions(+), 19 deletions(-) diff --git a/lib/perlsecret.ru.pod b/lib/perlsecret.ru.pod index 8f0c781..3fadcb3 100644 --- a/lib/perlsecret.ru.pod +++ b/lib/perlsecret.ru.pod @@ -433,38 +433,33 @@ https://ru.wikipedia.org/wiki/Дополнительный_код_(предст В некоторых случаях полный гоатсе не нужен, потому что нет необходимости для хранения значения в переменной. Побочный эффект списочного присвоения в скалярные контексте может быть получен I<правостороннем гоатсе> (C<()=>) -используется в скалярных контексте некоторых других значит чем assignement -к скалярным значением. +используемый в скалярных контексте имеет другое значение, чем присвоение + скаляру. Например: -In some cases, the full goaste is not needed, because there is no need -to store the value in a variable. The side-effect of list assignment in -scalar context can be obtained with a I (C<()=>) -used in a scalar context provided by some other mean than assignement -to a scalar. -For example: - - # remove empty array refs + + # удаление пустых ссылок на массивы @arrays = ( [], [1], [ 1, 2 ], [], [ 5 .. 9 ] ); # @filled = ( [1], [ 1, 2 ], [ 5 .. 9 ] ); @filled = grep +()= @$_, @arrays; -(The C<+> is in the above line is a no-op, used to tell C that the -parentheses are not enclosing its arguments.) +(C<+> в строке выше не операция, используется, что сказать C, +что скобки не включают его аргументы.) -Here's a convoluted example where C<=()=> seems to be the proper -construct to use, but it's actually another secret operator that -really does the trick. +Вот запутанный пример, где C<=()=> , представляется, как соответствующей +конструкцией для использования, но это на самом деле еще один секретный оператор, +в действительности это трюк. -Imagine you want to know in how many elements C<< split() >> would split -a string, but do not care about the elements themselves. Using C -in scalar context: +Представьте, что вы хотите знать, на сколько элементов C<< split() >> разобьет +строку, но не заботится о самих элементах. Используйте C<< split() >> +в скалярных контексте: my $count = split /:/, $string; -Gives the correct answer, but also a warning: +Дает правильный ответ, но и предупреждение: 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 From 8f45c23f1c48e9a7ff404799e7c7f50cf4d3b49f Mon Sep 17 00:00:00 2001 From: Nikolay Mishin Date: Mon, 20 Oct 2014 06:50:06 +0400 Subject: [PATCH 21/28] Update perlsecret.ru.pod --- lib/perlsecret.ru.pod | 119 ++++++++++++++++++++---------------------- 1 file changed, 58 insertions(+), 61 deletions(-) diff --git a/lib/perlsecret.ru.pod b/lib/perlsecret.ru.pod index 3fadcb3..0b35f51 100644 --- a/lib/perlsecret.ru.pod +++ b/lib/perlsecret.ru.pod @@ -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 never splits to more fields than necessary. -And the compiler interprets storing the results in C<()> as not caring -about the results, so C will B, -and thus return the full string, which gives a list of only one element -in scalar context, hence the C<1>. +Причина того, что C никогда не разбивается больше полей, чем необходимо. +И компилятор интерпретирует, сохранение результатов в C<()> , не заботясь о +о результатах, так C не будет B<разбивать строку на всё>, +и таким образом вернуть полную строку, которая дает список только одного элемента +в скалярном контексте, следовательно C<1>. -You have two options to address this. First, you can override C's -optimization by explicitly asking it to split into an unlimited number of -fields: +У вас есть два варианта решения этой проблемы. Во-первых можно переопределить C +оптимизацию, явно задавая его разделить на неограниченное число +полей: my $count =()= split /:/, $string, -1; -Or else you can defeat the optimization by using another secret operator -instead, the I: +Или же вы можете победить оптимизации с помощью другого секретного оператора +вместо этого I<детской коляской>: my $count = @{[ split /:/, $string ]}; -This causes C 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 обнаружить, что вызывающий объект может хранить любое количество +полей, таким образом он будет на самом деле делать работу до того, как анонимный +массив выбрасывается после использования в скалярном контексте. - -=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 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, таким образом, +возвращая одну строку ввода. - @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. +Как и другие операторы, основанные на скобочных конструкциях , кайт +контейнер и может нести полезную нагрузку (в данном случае, дескриптор файла). -Mnemonic: It provides a feature that is tied to one line, a string, -as it were. (Tye McQueen in L). +Обратите внимание, что когда дескриптор файла дочитан до конца, оператор кайт будет +возвращать пустую строку вместо C . +Мнемоника: Он обеспечивает функцию, которая привязана к одной строке, строке, +как она была. (Tye Маккуин в L). -=head2 Ornate double-bladed sword +=head2 Богатый двухлезвийный меч (Ornate double-bladed sword) <> 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<< >>: +Этот оператор обеспечивает многострочные комментарии, путем разумного использования +heredoc-синтаксиса и красивой симметрии. +Цитата C<< >>: <> - 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 ribbon with the C<;> throwing blade attached -to it. +"Орнамент" C ленты с C<;> бросает меч, привязанный к нему. -Note that the "commented" text is actually a double-quoted string in -void context, which can have some side effects. +Обратите внимание, что "комментируемый" текст на самом деле строка в двойных кавычках в + пустом контексте, что может иметь некоторые побочные эффекты. =head2 Screwdriver operators From 479b0e8930a54f93859409d1cf2ba7e5500b1462 Mon Sep 17 00:00:00 2001 From: Nikolay Mishin Date: Mon, 20 Oct 2014 07:12:43 +0400 Subject: [PATCH 22/28] Update perlsecret.ru.pod --- lib/perlsecret.ru.pod | 87 +++++++++++++++++++++++-------------------- 1 file changed, 47 insertions(+), 40 deletions(-) diff --git a/lib/perlsecret.ru.pod b/lib/perlsecret.ru.pod index 0b35f51..01ecc0f 100644 --- a/lib/perlsecret.ru.pod +++ b/lib/perlsecret.ru.pod @@ -22,10 +22,10 @@ Cекретный операторы Perl: =< >=~ Пылающий X-Wing Истребитель ищем во входных данных и присваиваем захваченное ~~<> Кайт, девочка убийца Одиночная строка ввода <> m ; Богатый двухлезвийный меч Многострочный комментарий - -=! -=!! Простак условное уменьшение - +=! +=!! Филипс условное увеличение + -=! -=!! Плоская условное уменьшение + +=! +=!! Прямоугольная условное увеличение x=! x=!! Крестовая условный резет на '' - *=! *=!! Торкс Шестилучевая отвертка условный резет на 0 + *=! *=!! Шестилучевая отвертка условный резет на 0 ,=> Подмигивающая жирная запятая не стрингифицирующая жирная запятая ()x!! Смелость Enterprise Сквош логического списка 0+!! Ключ к истине числовое преобразование логических значений @@ -567,88 +567,86 @@ heredoc-синтаксиса и красивой симметрии. Обратите внимание, что "комментируемый" текст на самом деле строка в двойных кавычках в пустом контексте, что может иметь некоторые побочные эффекты. -=head2 Screwdriver operators +=head2 Отверточный оператор (Screwdriver) -Discovered by Dmitry Karasik, 2007, while looking for C-based operators. +Открыт Дмитрием Карасиком, 2007, при поиске операторов, основанных на знаке C. -All screwdriver operators are conditional operators. Like screwdrivers, -they come in 4 major types, with different handle lengths. +Все отверточные операторы являются условными операторами. Как отвертки, +они приводятся к 4м основным типам, с различными длинами ручек. =over 4 =item * -Flathead +Плоская -=!! -=! -This operator provides conditional decrement: +Этот оператор обеспечивает условное уменьшение: $x -=!! $y # $x-- if $y; $x -=! $y # $x-- unless $y; =item * -Phillips +Прямоугольная +=!! +=! -This operator provides conditional increment: +Этот оператор обеспечивает условное увеличение: $x +=!! $y; # $x++ if $y; $x +=! $y; # $x++ unless $y; =item * -Torx +Шестилучевая *=!! *=! -This operator provides conditional reset to C<0>: +Этот оператор обеспечивает условный сброс на C<0>: $x *=!! $y; # $x = 0 unless $y; $x *=! $y; # $x = 0 if $y; -The torx screwdriver operator does not work properly with negative numbers -different from C<-1> on Perl versions lower than or equal to 5.13.5. -It also fails with C<-1> on Perl versions lower than or equal to 5.7.0. +Оператор шестилучевая отвертка не работает должным образом с отрицательными числами +отличными от C<-1> на Perl версии ниже или равно, чем 5.13.5. +Он также не удается с C<-1> на Perl версии ниже или равной 5.7.0. =item * -Pozidriv +Крестовая x=!! x=! -This operator provides conditional reset to C<''>: +Этот оператор обеспечивает условный сброс на C<''>: $x x=!! $y; # $x = '' unless $y; $x x=! $y; # $x = '' if $y; -(This one was discovered by Philippe Bruhat in 2009, while preparing a -talk about the secret operators.) +(Это один был обнаружен Филиппом Брюа в 2009 году, при подготовке +лекции о тайных (секретных) операторах.) =back -Mnemonic: the screwdriver's head is the best mnemonic (C<-> and C<+> -for increment and decrement, C<*> for the null number, C for the -null string). +Мнемоника: головка отвертки является лучшим мнемоникой ческие (C<-> and C<+> +для инкремента и декремента, C<*> для несуществующего значения (null), C для пустой строки). - -=head2 Winking fat comma +=head2 Подмигивающая жирная запятая (Winking fat comma) ,=> -Discovered by Abigail, 2010. -(Alternate nickname: "grappling hook") +Открыта Абигалем, 2010. +(Альтернативное имя: "крюк" "grappling hook") -Visually looks like a fat comma, but without the left-hand side behaviour. +Визуально выглядит как жирная запятая, но без левой стороннего поведения. -This operator is used to retain the documenting features of the fat comma, -while disabling the string interpretation of the word to its left. +Этот оператор используется для сохранения документированной особенности жирной запятой, +при отключении строкового толкования слова слева. use constant APPLE => 1; use constant CHERRY => 2; @@ -660,20 +658,20 @@ while disabling the string interpretation of the word to its left. BANANA ,=> "yellow", ); -is equivalent to: +эквивалентно: %hash = ( 1, "green", 2, "red", 3, "yellow" ); -Mnemonic: the comma C<,> is an off-switch for the fat comma's stringification. +Мнемоника: запятая C <,> является выключателем для жирной запятой в ее стрингификации (приведении к строке). -=head2 Enterprise +=head2 Предприятие (Enterprise) ( )x!! -Discovered by Aristotle on PerlMonks, 2006. -(Alternate nicknames: "NCC-1701", "snail") +Обнаружил Аристотель на PerlMonks, 2006. +(Альтернативный ник: «NCC-1701», «улитка» "snail") -It is often necessary to conditionally include items in a list: +Часто необходимо условно включать элементы в список: my @shopping_list = ('bread', 'milk'); push @shopping_list, 'apples' if $cupboard{apples} < 2; @@ -681,8 +679,8 @@ It is often necessary to conditionally include items in a list: push @shopping_list, 'cherries' if $cupboard{cherries} < 20; push @shopping_list, 'tonic' if $cupboard{gin}; -The Enterprise lets you build the list and add only the items that -match the condition, in a single statement: +Предприятия позволяет создавать список и добавлять только элементы, +которые удовлетворяет условию, в одной инструкции: my @shopping_list = ( 'bread', @@ -693,8 +691,17 @@ match the condition, in a single statement: ('tonic' )x!! $cupboard{gin}, ); -This operator is a container, which means the Enterprise can have a -large crew. +Этот оператор представляет собой контейнер, а это значит, предприятие может иметь +большой экипаж. + +Предприятие это просто повторение списочного оператора C<< ()x >> +затем логическое значение (см L L<Двойной удар> оператор выше), который будет +интерпретируется как 1 или 0 в числовом контексте. +Следует отметить, что выражение слева всегда оценивается, независимо от того, +состояние состоянии. + +Из вопросов приоритета, сложных условиях на хвосте +Предприятие может потребоваться поставить в скобки. The Enterprise is simply a list repetition operator C<< ()x >> followed by a boolean (see the L operator above) which will be From 17dfce431f7daa2d42a0d500f63d93743181cc1c Mon Sep 17 00:00:00 2001 From: Nikolay Mishin Date: Mon, 20 Oct 2014 09:54:48 +0400 Subject: [PATCH 23/28] Update perlsecret.ru.pod --- lib/perlsecret.ru.pod | 159 ++++++++++++++++++++---------------------- 1 file changed, 75 insertions(+), 84 deletions(-) diff --git a/lib/perlsecret.ru.pod b/lib/perlsecret.ru.pod index 01ecc0f..7a88325 100644 --- a/lib/perlsecret.ru.pod +++ b/lib/perlsecret.ru.pod @@ -10,27 +10,27 @@ Cекретный операторы Perl: Оператор Кличка Функция ====================================================== - 0+ Венус Venus Приведение к цифре - @{[ ]} Детскаякаляска Babycart интерполяция списка - !! 2 удара Bang bang логическое преобразование - }{ Эскимосское приветствие КОНЕЦ блока для однострочного скрипта - ~~ Дюймовыйчервь Inchworm скалярный - ~- Дюймовыйчервь на палке декремент высокого приоритета - -~ Дюймовыйчервь на палке декремент высокого приоритета - -+- Космическая станция Приведение к цифре высокого приоритета - =( )= Гоатсе скалярный / списочный контекст - =< >=~ Пылающий X-Wing Истребитель ищем во входных данных и присваиваем захваченное - ~~<> Кайт, девочка убийца Одиночная строка ввода - <> m ; Богатый двухлезвийный меч Многострочный комментарий - -=! -=!! Плоская условное уменьшение - +=! +=!! Прямоугольная условное увеличение - x=! x=!! Крестовая условный резет на '' - *=! *=!! Шестилучевая отвертка условный резет на 0 - ,=> Подмигивающая жирная запятая не стрингифицирующая жирная запятая - ()x!! Смелость Enterprise Сквош логического списка - 0+!! Ключ к истине числовое преобразование логических значений + 0+ Венус Venus Приведение к цифре + @{[ ]} Детскаякаляска Babycart интерполяция списка + !! 2 удара Bang bang логическое преобразование + }{ Эскимосское приветствие КОНЕЦ блока для однострочного скрипта + ~~ Дюймовыйчервь Inchworm скалярный + ~- Дюймовыйчервь на палке декремент высокого приоритета + -~ Дюймовыйчервь на палке декремент высокого приоритета + -+- Космическая станция Приведение к цифре высокого приоритета + =( )= Гоатсе скалярный / списочный контекст + =< >=~ Пылающий X-Wing Истребитель ищем во входных данных и присваиваем захваченное + ~~<> Кайт, девочка убийца Одиночная строка ввода + <> m ; Богатый двухлезвийный меч Многострочный комментарий + -=! -=!! Плоская условное уменьшение + +=! +=!! Прямоугольная условное увеличение + x=! x=!! Крестовая условный резет на '' + *=! *=!! Шестилучевая отвертка условный резет на 0 + ,=> Подмигивающая жирная запятая не стрингифицирующая жирная запятая + ()x!! Предприятие Enterprise Сквош логического списка + 0+!! Ключ к истине числовое преобразование логических значений ||() Эбботт и Костелло Камеди дуэт удалить ложный скаляр из списка - //() Наклон Эбботта и Костелло удалить undef из списка + //() Наклонный Эбботта и Костелло удалить undef из списка Perl секретные константы: @@ -697,41 +697,31 @@ heredoc-синтаксиса и красивой симметрии. Предприятие это просто повторение списочного оператора C<< ()x >> затем логическое значение (см L L<Двойной удар> оператор выше), который будет интерпретируется как 1 или 0 в числовом контексте. -Следует отметить, что выражение слева всегда оценивается, независимо от того, -состояние состоянии. +Следует отметить, что выражение слева всегда выполняется, независимо от условия. -Из вопросов приоритета, сложных условиях на хвосте -Предприятие может потребоваться поставить в скобки. +Из-за вопросов приоритета, сложных условиях в конце +оператора ентерпрайз (предприятия) может потребоваться поставить в скобки. -The Enterprise is simply a list repetition operator C<< ()x >> -followed by a boolean (see the L operator above) which will be -interpreted as 1 or 0 in a numeric context. -Note that the expression on the left is always evaluated, regardless of -the state of the condition. - -Because of precedence issues, complex conditions on the tail of the -Enterprise may need to be put between parentheses. - -=head2 Key to the truth +=head2 Ключ к истине (Key to the truth) 0+!! -Discovered by Toby Inkster, 2013. +Обнаружен Тоби Инкстер, 2013. -This operator is a combination of the Venus and bang bang operators. -It simply makes the boolean false into the C<0> numeric value. +Этот оператор - комбинация операторов Венеры (Venus), и двойного удара(bang bang). +Он просто превращает логическую ложь числовое значение C<0>. - my $true = 0+!! 'a string'; # now 1 - my $false = 0+!! undef; # now 0 + my $true = 0+!! 'a string'; # теперь 1 + my $false = 0+!! undef; # теперь 0 -=head2 Abbott and Costello +=head2 Эбботт и Костелло Камеди дуэт ||() -Discovered by Yves Orton. +Обнаружен Ивом Ортоном. -This operator makes a false value disappear in list context. -It simply replaces a false scalar by the empty list. +Этот оператор делает ложное значение исчезающим в списочном контексте. +Он просто заменяет ложный скаляр пустым списком. my @shopping_list = ( 'bread', @@ -741,94 +731,95 @@ It simply replaces a false scalar by the empty list. 'apples' ); -Mnemonic: one is tall (and also the "straight man") and one is fat, -just like the famous comedy duo. +Мнемоника: один высокий, (а также "прямой человек") и один жирный, +, как в известном комедийном дуэте. -=head2 Leaning Abbott and Costello +=head2 Наклонный Эбботта и Костелло //() -Proposed by Damien Krotkine, 2014. +Предложен Дэмиеном Кроткиным, 2014. -This operator works exactly like the L, except -that it only makes C disappear in list context. +Этот оператор работает точно так же, как L<Эбботт и Костелло> , за исключением +того, что он только делает C исчезающим в списочном контексте. -This operator only works in Perl versions above 5.10. +Этот оператор работает только в версиях Perl 5.10 выше. -Mnemonic: in this version, the "straight man" is leaning -(and so the associativity is really "(leaning Abbott) and Costello"). +Мнемоника: в этой версии, "прямой человек" склоняется +(и, поэтому, реальная ассоциативность "(склюняющийся Эботт) и Костелло" ). -=head1 SECRET CONSTANTS +=head1 СЕКРЕТНЫЕ КОНСТАНТЫ -=head2 Space fleet +=head2 Космический флот (Space fleet) <=><=><=> -Discovered by Damian Conway. +Открыт Домианом Конвеем. -Even though it looks like a sequence of three spaceship operators, -only the middle ship is an actual spaceship. The two outer "spaceships" -are actually calls to C. +Даже несмотря на то, что он выглядит как последовательность из трех космических кораблей, +только средний корабль является фактическим кораблем. Два внешних "корабля" +являются на самом деле вызовом C. -This constant has the value C<0>. +Эта константа имеет значение C<0>. -=head2 Amphisbaena +=head2 Амфисбена Двойной путь (Amphisbaena) <~> + +Обнаружил Рафаэль Гарсия Суарес, 2009. -Discovered by Rafaël Garcia-Suarez, 2009. +Под Unix будет равна в домашнему каталогу пользователя (с помощью C ). +На Win32 он будет расширять C<$ENV{HOME}>, если он установлен (что является довольно редко) +или возвратит C<'~'>. -Under Unix, will be equal to the real user home directory (by using C). -On Win32 it will expand to C<$ENV{HOME}> if it is set (which is quite uncommon) -or return C<'~'> else. +=head1 АВТОР -=head1 AUTHOR +Филипп Брюа (книга) -Philippe Bruhat (BooK) +=head1 БЛАГОДАРНОСТИ -=head1 ACKNOWLEDGMENTS - -The author would like to thank José Castro, Andrew Savige, Dmitry +Автор хотел бы поблагодарить José Castro, Andrew Savige, Dmitry Karasik, Abigail, Yitzchak Scott-Thoennes, Zefram, Tye McQueen, Maxim Vuets, Aristotle Pagaltzis, Toby Inkster, Ævar Arnfjörð Bjarmason, Rafaël Garcia-Suarez, Andreas J. König, Andy Armstrong, Pau Amma, Keith C. Ivey, Michael R. Wolf, Olivier Mengué, Yves Orton, Damien Krotkine, -Diab Jerius, Ivan Bessarabov -and the Fun With Perl mailing list for inspiration, suggestions and patches. +Diab Jerius, Ивана Бессарабова +и ожидает (Fun) в списке рассылки Perl вдохновения, предложений и патчей. + -=head1 CONTRIBUTING +=head1 СПОСОБСТВОВАНИЕ -If you know of other secret operators or constants, please let me know! +Если вы знаете другие тайные операторы и константы, пожалуйста, дайте мне знать! -However, before sending me your latest creation, be aware that, although -these are not set in stone, I consider the following criteria before -adding an operator or constant to this list: +Однако, прежде чем отправить мне ваше последнее творение, следует знать, что, хотя +они устанавливаются не в камне, я считаю следующие критерии до +добавление оператора или константы в этот список: =over 4 =item * -does it have a nickname? (usually one that matches its ASCII-art shape) +имеет ли он ник? (обычно такое, которое соответствует его художественной ASCII форме), =item * -is it actually used in the wild? +используется ли он на самом деле в дикой природе? =item * -does it have a golf-specific interest? (i.e. does it perform some useful -operation in significantly fewer characters than "normal" Perl code?) +имеет ли он гольф-специфичный интерес? (т.е. он выполняет некоторые полезные +операция в значительно меньше числе символов, чем "нормального" Perl код?) =item * -does it have some historical interest? +имеет ли он исторический интерес? =back -=head1 REFERENCES +=head1 ССЫЛКИ -As shown below, most of the secret operator action happens -on the Fun With Perl mailing-list. +Как показано ниже, большинство действий секретных операторов происходит +в веселом списке рассылки Perl. =over 4 From 81f86032e1f65a637ae94e3337ffd77d2c882986 Mon Sep 17 00:00:00 2001 From: Nikolay Mishin Date: Mon, 20 Oct 2014 11:41:31 +0400 Subject: [PATCH 24/28] Update perlsecret.ru.pod --- lib/perlsecret.ru.pod | 90 +++++++++++++++++++++++-------------------- 1 file changed, 48 insertions(+), 42 deletions(-) diff --git a/lib/perlsecret.ru.pod b/lib/perlsecret.ru.pod index 7a88325..e34248b 100644 --- a/lib/perlsecret.ru.pod +++ b/lib/perlsecret.ru.pod @@ -825,118 +825,119 @@ Diab Jerius, Ивана Бессарабова =item * -Around 1993, according to Randal Schwartz in his "I" -talk given on July 25, 2013 at OSCON: +В 1993 году, по словам Рэндала Шварца в его "I<Мои пол-жизни с Perl>" ("I") + 25 июля 2013 на OSCON был доклад: +I<Дочь Ларри (Женева?) названный EE оператор для меня (Я назвал E=E)> IE operator for me (I named the E=E)> =item * Post C<< <1994May1.035104.25990@netlabs.com> >> in C -Larry Wall discovers the baby cart and describes it as "a way to -interpolate function results into a string". +Ларри Уолл обнаруживает детскую коляску и описывает ее, как «путь, +интерполирующий результаты функции в строку". =item * -Post C<< >> in C +Сообщение C<< >> in C -Abigail coins the term "secret operator" to describe C<< <> m ; >>. +Абигейл вводит термин "секретный оператор", чтобы описать C<< <> m ; >>. =item * L -Original "secret operators" thread. -Several of the detailed explanations in this manual page come from this thread. +Оригинальное обсуждение "секретных операторов". +Несколько из подробных объяснений на этой странице пришли из этого обсуждения. =item * L -Description of the space station operator. +Описание оператора космической станции. =item * L -Philippe Bruhat uses the word "venus" to describe C<0+>. +Филипп Брюа использует слово "Венера"("venus"), чтобы описать C<0+>. =item * L -Naming the baby cart operator. +Именование оператора детксая коляска(baby cart). =item * L -Aristotle Pagaltzis explains how the baby cart can be used to break aliasing. +Аристотель Пэгэлцис объясняет, как детская коляска может использоваться, чтобы сломать совмещение имен(break aliasing). =item * L -I, -by Aristotle Pagaltzis, describes the Enterprise operator. +I<Секретные Операторы Perl: логический оператор список сквош, x!!>, +Аристотель Пэгэлцис, описывает оператор предприятия(энтерпрайз). =item * L -Description of the flaming X-Wing secret operator. +Описание тайного оператора пылающий X-Wing. =item * L -Description of the screwdriver operators, and other C-based operators. +Описание операторов отвертки и других, основанных на символе C. =item * L -Description of the fourth screwdriver operator (Pozidriv). +Описание четвертого оператора отвертки (позидрайв - крестовой). =item * L -Description of the sperm/kite operator. +Описание оператора спермы/кайт. =item * L -Proposal for an alternate, family-friendly, nickname for the goatse -operator, with a second order inside joke. +Предложение по дополнительному, благоприятному для семьи, нику для оператора гоатсе +, со вторым набором шуток внутри. =item * -The Abbott and Costello operator was first presented to me on 2013-09-25 -by Yves Orton in private messages. +Эбботт и Костелло оператор был впервые представлен мне 2013-09-25 +Ивом Ортоном в личных сообщениях. -I tried to propose "Laurel and Hardy" as a more internationally -understable alternative, but it turns out Hardy is I the fat and -the tall one. +Я пытался предложить «Лорел и Харди» как более международную и понятную +альтернативу, но оказывается Харди I<оба> жирные и +высокие в одном лице. =item * -The key to the truth operator was described to me on 2013-09-28 -by Toby Inkster on the C<#moose> IRC channel and private messages. +Ключ к оператору правды был описан мне 2013-09-28 +Тоби Инкстером на C<#moose> IRC канале и в личных сообщениях. =item * -On 2014-02-18, on the C<#perlfr> IRC channel, Damien Krotkine notes that -he uses C more than C<||()>, to which Philippe Bruhat answers -immediately with the name "Leaning Abbot and Costello", noting that -Abbot is the tall one. +2014-02-18, на C<#perlfr> IRC канале, Дамиан Кроткин отмечает, что +он использует C чаще, чем C<||()>, на который отвечает Филипп Брюа +немедленно с именем "Наклоняющийся Аббат и Костелло", отмечая это +Аббат - высокий. =back -More secret operators didn't make it to this list, because they -don't have a name yet. +Более тайные операторы не попали в этот список, потому что у них +пока нет имени. =over 4 @@ -944,19 +945,24 @@ don't have a name yet. L -The fwp post that presents the screwdriver operators also presents a -few more C-based operators. +Пересылка сообщения, которое представляет отверточные операторы, также представляет +несколько больше операторов, основанных на C. =back -=head1 COPYRIGHT +=head1 АВТОРСКОЕ ПРАВО -Copyright 2010-2014 Philippe Bruhat (BooK). +Copyright 2010-2014 Philippe Брюа (книга). -=head1 LICENSE +=head1 ЛИЦЕНЗИЯ -This documentation is free; you can redistribute it and/or modify it -under the same terms as Perl itself. - -=cut +Эта документация предоставляется бесплатно; вы можете распространять её и/или изменить её +на тех же условиях как и сам Perl. +=head1 ПЕРЕВОДЧИКИ + +=over + +=item * Николай Мишин C<< >> + +=back From 5b367b598869ff3ca0e190c3bd281d9b1bd31414 Mon Sep 17 00:00:00 2001 From: Nikolay Mishin Date: Mon, 20 Oct 2014 16:24:25 +0400 Subject: [PATCH 25/28] Update perlsecret.ru.pod --- lib/perlsecret.ru.pod | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/perlsecret.ru.pod b/lib/perlsecret.ru.pod index e34248b..1910015 100644 --- a/lib/perlsecret.ru.pod +++ b/lib/perlsecret.ru.pod @@ -42,7 +42,7 @@ Perl секретные константы: =head1 ОПИСАНИЕ Perl имеет давнюю традицию давать прозвища для некоторых из своих операторов -(возможноя форма очеловечивания). Эти прозвища основаны на +(возможнfя форма очеловечивания). Эти прозвища основаны на скорее на виде оператора, чем на его функции. Известные примеры I<бриллиантовый оператор> (C<< <> >>), по прозвищу Стена Женевы и I<оператор космического корабля> (C<< <=> >>), From 13fabebf95ba0c8718883dd5917c8f2ce5eaa6ce Mon Sep 17 00:00:00 2001 From: Nikolay Mishin Date: Mon, 20 Oct 2014 16:26:13 +0400 Subject: [PATCH 26/28] Update perlsecret.ru.pod --- lib/perlsecret.ru.pod | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/perlsecret.ru.pod b/lib/perlsecret.ru.pod index 1910015..798fdc2 100644 --- a/lib/perlsecret.ru.pod +++ b/lib/perlsecret.ru.pod @@ -42,8 +42,8 @@ Perl секретные константы: =head1 ОПИСАНИЕ Perl имеет давнюю традицию давать прозвища для некоторых из своих операторов -(возможнfя форма очеловечивания). Эти прозвища основаны на -скорее на виде оператора, чем на его функции. +(возможная форма очеловечивания). Эти прозвища основаны на +скорее на виде операторов, чем на их функциях. Известные примеры I<бриллиантовый оператор> (C<< <> >>), по прозвищу Стена Женевы и I<оператор космического корабля> (C<< <=> >>), прозванный Рендаль Шварц. From bfe6f5b09bf45bab8dbffb435b9ba830f55b2e05 Mon Sep 17 00:00:00 2001 From: Nikolay Mishin Date: Wed, 22 Oct 2014 09:11:23 +0400 Subject: [PATCH 27/28] Update perlsecret.ru.pod --- lib/perlsecret.ru.pod | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/lib/perlsecret.ru.pod b/lib/perlsecret.ru.pod index 798fdc2..1df57c3 100644 --- a/lib/perlsecret.ru.pod +++ b/lib/perlsecret.ru.pod @@ -6,7 +6,7 @@ perlsecret - Cекретные операторы и константы Perl =head1 КРАТКИЙ ОБЗОР -Cекретный операторы Perl: +Cекретные операторы Perl: Оператор Кличка Функция ====================================================== @@ -14,9 +14,9 @@ Cекретный операторы Perl: @{[ ]} Детскаякаляска Babycart интерполяция списка !! 2 удара Bang bang логическое преобразование }{ Эскимосское приветствие КОНЕЦ блока для однострочного скрипта - ~~ Дюймовыйчервь Inchworm скалярный - ~- Дюймовыйчервь на палке декремент высокого приоритета - -~ Дюймовыйчервь на палке декремент высокого приоритета + ~~ Дюймочервь Inchworm скалярный + ~- Дюймочервь на палке декремент высокого приоритета + -~ Дюймочервь на палке декремент высокого приоритета -+- Космическая станция Приведение к цифре высокого приоритета =( )= Гоатсе скалярный / списочный контекст =< >=~ Пылающий X-Wing Истребитель ищем во входных данных и присваиваем захваченное @@ -53,13 +53,13 @@ Perl имеет давнюю традицию давать прозвища дл "I" Perl были обнаружены (или созданы) Perl обфускаторами и Perl гольфистами, обычно при поиске более короткого пути выполнения операции. -Секретный операторы не являются на самом деле секретными, и они не являются на самом деле +Секретные операторы не являются на самом деле секретными, и они не являются на самом деле операторами. Perl анализатор специально не признает их, и не пытается скрывать их от вас. -Но они, являются операторами в том смысле, Perl программистам достаточно посмотреть +Но они, являются операторами в том смысле, что Perl программистам достаточно посмотреть на их конструкцию, чтобы понять, что они делают, не задумываясь о более мелких элементах - и в конечном итоге добавляют их в свою коллецию инструментов. -Они являются секретами в том смысле, что они должны обнаружены + и они в конечном итоге добавляют их в свою коллецию инструментов. +Они являются секретами в том смысле, что они должны быть обнаружены их будущем пользоватем (программистом), потому что они явно не описаны в основной документации Perl. From b59b1f47cbb125df95bae34525db1d0f3f7ac90a Mon Sep 17 00:00:00 2001 From: Nikolay Mishin Date: Tue, 9 Jun 2015 09:37:17 +0300 Subject: [PATCH 28/28] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=BE=D0=BF=D0=B5=D1=87=D0=B0=D1=82=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/perlsecret.ru.pod | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/perlsecret.ru.pod b/lib/perlsecret.ru.pod index 1df57c3..fdc4a92 100644 --- a/lib/perlsecret.ru.pod +++ b/lib/perlsecret.ru.pod @@ -42,7 +42,7 @@ Perl секретные константы: =head1 ОПИСАНИЕ Perl имеет давнюю традицию давать прозвища для некоторых из своих операторов -(возможная форма очеловечивания). Эти прозвища основаны на +(возможная форма очеловечивания). Эти прозвища основаны скорее на виде операторов, чем на их функциях. Известные примеры I<бриллиантовый оператор> (C<< <> >>), по прозвищу Стена Женевы и I<оператор космического корабля> (C<< <=> >>),