Skip to content

Commit b36a6b2

Browse files
committed
add info on space probs with function call format
1 parent c3de8f2 commit b36a6b2

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

doc/Language/traps.pod

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,53 @@ The loose precedence of C<..> can lead to some errors. It is usually best to pa
248248
1..3.say # says "3" (and warns about useless "..")
249249
(1..3).say # says "1..3"
250250
251+
=head1 Subroutine and method calls
252+
253+
Subroutine and method calls can be made using one of two forms:
254+
255+
foo(...); # function call form, where ... represent the required arguments
256+
foo ...; # list op form, where ... represent the required arguments
257+
258+
The function call form can cause problems for the unwary when
259+
whitespace is added after the function or method name and before the
260+
opening parenthesis.
261+
262+
First we consider functions with zero or one parameter:
263+
264+
sub foo() { say 'no arg' }
265+
sub bar($a) { say "one arg: $a" }
266+
267+
Then execute each with and without a space after the name:
268+
269+
foo(); # okay: no arg
270+
foo (); # FAIL: Too many positionals passed; expected 0 arguments but got 1
271+
bar($a); # okay: one arg: 1
272+
bar ($a); # okay: one arg: 1
273+
274+
Now declare a function of two parameters:
275+
276+
sub foo($a, $b) { say "two args: $a, $b" }
277+
278+
Execute it with and without the space after the name:
279+
280+
foo($a, $b); # okay: two args: 1, 2
281+
foo ($a, $b); # FAIL: Too few positionals passed; expected 2 arguments but got 1
282+
283+
The lesson is: "be careful with spaces following sub and method names
284+
when using the function call format." As a general rule, good
285+
practice might be to avoid the space after a function name when using
286+
the function call format.
287+
288+
Note that there are clever ways to eliminate the error with the
289+
function call format and the space, but that is bordering on hackery
290+
and will not be mentioned here. For more information, consult
291+
L<Functions|/language/functions#Functions>.
292+
293+
Finally, note that, currently, when declaring the functions whitespace
294+
may be used between a function or method name and the parentheses
295+
surrounding the parameter list without problems (although that may
296+
change in the future).
297+
251298
=end pod
252299

253300
# vim: expandtab shiftwidth=4 ft=perl6

0 commit comments

Comments
 (0)