Skip to content

Commit

Permalink
Merge pull request #1594 from fluca1978/method-precedence-drop
Browse files Browse the repository at this point in the history
Add a short introduction to subroutines and precedence dropping.
  • Loading branch information
rafaelschipiura committed Oct 11, 2017
2 parents dc65648 + 69d7951 commit 135102b
Showing 1 changed file with 38 additions and 5 deletions.
43 changes: 38 additions & 5 deletions doc/Language/syntax.pod6
Expand Up @@ -644,7 +644,13 @@ Inside of a class, you can also declare multi-dispatch methods.
=head1 Subroutine calls
See L<functions|/language/functions>.
Subroutines are created with the keyword C<sub> followed
by an optional name, an optional signature and a code block.
Subroutines are lexically scoped, so if a name is specified
at the declaration time, the same name can be used
in the lexical scope to invoke the subroutine.
A subroutine is an instance of type L<Sub|type/Sub> and
can be assigned to any container.
=comment TODO
Expand All @@ -654,16 +660,43 @@ See L<functions|/language/functions>.
&f(); # Invoke &f, which contains a function
&f.(); # Same as above, needed to make the following work
my @functions = ({say 1}, {say 2}, {say 3});
@functions>>.();
@functions>>.(); # hyper method call operator
=end code
When declared within a class, a subroutine is named "method": methods
are subroutines invoked against an object (i.e., a class instance).
Within a method the special variable C<self> contains the object instance
(see L<Methods|classtut#Methods>).
=begin code :skip-test
# Method invocation. Object (instance) is $person, method is set-name-age
$person.set-name-age('jane', 98); # Most common way
$person.set-name-age: 'jane', 98; # Precedence drop
set-name-age($person: 'jane', 98); # Invocant marker
$person.set-name-age('jane', 98); # Most common way
$person.set-name-age: 'jane', 98; # Precedence drop
set-name-age($person: 'jane', 98); # Invocant marker
=end code
For more information see L<functions|/language/functions>.
=head 2 Precedence Drop
In the case of method invocation (i.e., when invoking a subroutine against
a class instance) it is possible to apply the C<precedence drop>, identified
by a colon C<:> just after the method name and before the argument list.
The argument list takes precedence over the method call, that on the other
hand "drops" its precedence. In order to better understand consider
the following simple example (extra spaces have been added just to align
method calls):
=begin code :skip-test
my $band = 'Foo Fighters';
say $band.substr( 0, 3 ) .substr( 0, 1 ); # F
say $band.substr: 0, 3 .substr( 0, 1 ); # Foo
=end code
In the second method call the rightmost C<substr> is applied to "3" and not
to the result of the leftmost C<substr>, which on the other hand yields precedence
to the rightmost one.
=head1 Operators
See L<Operators|/language/operators> for lots of details.
Expand Down

0 comments on commit 135102b

Please sign in to comment.