From aed55537bb5fa39788b14a95e6e51dd0feb51d8c Mon Sep 17 00:00:00 2001 From: Moritz Lenz Date: Wed, 10 Mar 2010 06:29:45 +0100 Subject: [PATCH] [operators] precedence --- Makefile | 1 + src/operators.pod | 60 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/Makefile b/Makefile index c91de53..2859652 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,6 @@ CHAPTERS =src/preface.pod \ src/basics.pod \ + src/operators.pod \ src/multi-dispatch.pod \ src/classes-and-objects.pod \ src/regexes.pod \ diff --git a/src/operators.pod b/src/operators.pod index 9bdc1d0..23f2b21 100644 --- a/src/operators.pod +++ b/src/operators.pod @@ -216,4 +216,64 @@ returns the value of the current pair, C<($unit * .value)> multiplies that values with C<$unit>, and C<'X' x ($unit * .value)> returns as that many C characters. +=head1 A Word on Precedence + +X +X + +The explanations of the example above have one implication, which was not yet +explicitly mentioned. In the line + +=begin programlisting + + my @scores = 'Ana' => 8, 'Dave' => 6, 'Charlie' => 4, 'Beth' => 4; + +=end programlisting + +The right-hand side of the assignment produces a list (because of the C<,> +operator) that is made of pairs (because of C<< => >>), and the result is then +assigned to the array variable. But you could think of +other ways that Perl 6 interprets this program. If you pass this line to the +Perl 5 interpreter, it parses it as + +=begin programlisting + + (my @scores = 'Ana') => 8, 'Dave' => 6, 'Charlie' => 4, 'Beth' => 4; + +=end programlisting + +and thus stores only one item in the variable C<@scores>, the rest is +parsed as a list N. + +The ways in which this statement is parsed in Perl 6 is governed by +I. For example they state that the infix C<< => >> operator +binds its arguments tighter than the infix C<,> operator, which in turn binds +tighter than the C<=> assignment operator N with tighter precedence is used. This allows the two expressions C<$a = 1, $b = 2> +and C<@a = 1, 2> to both mean something sensible: assignment to two variables in a list, +and assignment of a two-item list to a single variable>. + + +The precedence rules for Perl 6 allow very natural expression of many commonly +used idioms without any parenthesis, or even without thinking about +precedence. If you want to force a different way of parsing, parenthesis can +be used around an expression. Then this parenthesis group has the tightest +possible precedence. + +=begin programlisting + + say 5 - 7 / 2; # 5 - 3.5 = 1.5 + say (5 - 7) / 2; # (-2) / 2 = -1 + +=end programlisting + +=for author + + TODO: list of precedence levels? + +=end for + + =for vim: spell