- Timestamp:
- 09/20/08 23:52:33 (4 months ago)
- Files:
-
- 1 modified
-
docs/tutorial/ch05_subroutines.pod (modified) (23 diffs)
Legend:
- Unmodified
- Added
- Removed
-
docs/tutorial/ch05_subroutines.pod
r22301 r22302 134 134 parameter to be passed in on every call isn't nearly flexible enough 135 135 for the average programmer, Perl 6 also allows optional parameters. 136 Each optional parameter is marked with a C<?> before the parameter 137 name: 136 Optional parameters can be included or ignored without causing any 137 errors. Each optional parameter is marked with a C<?> before the 138 parameter name: 138 139 139 140 sub someopt ($required1, $required2, ?$optional1, ?$optional2) { … … 152 153 someopt('req1', 'req2', 'opt1'); 153 154 someopt('req1', 'req2'); 155 156 Notice that it will still cause an error to pass too many or too few 157 parameters in a list with optional parameters: 158 159 someopt('req1') # WRONG! 160 someopt('req1', 'req2', 'opt1', 'opt2', 'extra') # WRONG! 154 161 155 162 =head2 Named Parameters … … 181 188 parameters to find the positional parameter list. 182 189 190 If it makes more sense to do it, you can also use the alternate key 191 syntax for passing parameters: 192 193 namedparams(1, :second(2), :third(3)) # Right 194 195 Also, named parameters aren't positional, you can pass them in any 196 orderN<Any order, so long as all the named parameters come after all 197 the positional parameters, of course>. So, we can pass the second third 198 and the third second: 199 200 namedparams(1, third => 3, second => 2) 201 202 The point of having a name for your parameter is that you don't have to 203 worry about the position of it. 204 183 205 =head2 Variadic Parameters 184 206 … … 193 215 C<*> before the parameter name will slurp up all the I<positional> 194 216 arguments that haven't already been bound to another positional 195 parameter .N<You may notice that this is the same symbol as the217 parameterN<You may notice that this is the same symbol as the 196 218 flattening/slurping operator in A<CHP-4-SECT-2.12>"Referencing (or 197 Not)" in Chapter 4.> So, the following call to C<transport> binds219 Not)" in Chapter 4.>. So, the following call to C<transport> binds 198 220 C<$arthur> to C<@names[0]>, and C<$ford> to C<@names[1]>: 199 221 … … 215 237 parameter. So, the following call to C<transport> binds the value of 216 238 the pair argument with the key C<'planet'> to the parameter 217 C< $planet>, but all the other pairs become part of the C<%flags> hash239 C<:$planet>, but all the other pairs become part of the C<%flags> hash 218 240 (more on this in A<CHP-5-SECT-3.1>"Named Argument Passing" later in 219 241 this chapter). 220 242 221 sub transport ( $planet, *%flags) {...}243 sub transport (:$planet, *%flags) {...} 222 244 223 245 transport('name' => 'Arthur', … … 227 249 228 250 When they're combined with other kinds of parameters, variadic 229 parameters must come after all positional parameters in the signature. 230 They can either precede or follow the named parameters. 251 positional parameters must come after all positional parameters in 252 the signature. They can either precede or follow the named parameters. 253 Variadic named parameters only slurp up the named parameters that aren't 254 bound already, so they can appear anywhere in the signatureN<anywhere 255 after all the positionals, of course.>. 231 256 232 257 =head2 Typed Parameters … … 238 263 Signature checking is sensitive not only to the number of arguments 239 264 and the variable type (defined by the C<$>, C<@>, C<%>, or C<&> 240 symbol), but also to the value type .N<See A<CHP-4-SECT-1.8>"Types" in241 Chapter 4 for more details on value and variable types.> The parameter265 symbol), but also to the value typeN<See A<CHP-4-SECT-1.8>"Types" in 266 Chapter 4 for more details on value and variable types.>. The parameter 242 267 type is defined before the parameter name and before any symbols for 243 268 optional, named, or variadic parameters: … … 266 291 modified within the body of the subroutine. The C<is rw> property 267 292 marks a parameter as modifiable, so changes to the parameter within 268 the body of the sub modify the original variable passed in: 293 the body of the sub modify the original variable passed in: 269 294 270 295 sub modifyparams ($first is rw, $second is rw) {...} 296 297 Be careful about using the C<is rw> property unless it's necessary, 298 inadvertent changes in a subroutine can change data values in the 299 caller's scope that might not be expecting to be changed. At the 300 very least, it's polite to document it when your subroutine is monkeying 301 around in somebody else's scope. 271 302 272 303 The C<is copy> property marks a parameter as pass-by-value, so the … … 274 305 275 306 sub passbyvalue ($first is copy, $second is copy) {...} 276 307 308 This means that the parameter is not an alias for the value in the 309 caller's scope, but it's not read-only either. It's a new variable, 310 a copy of the original and free to be used however your subroutine 311 sees fit. 312 277 313 =head2 Default Values for Parameters 278 314 … … 282 318 Sometimes it is useful to be able to define a default value for an 283 319 optional or named parameter. The C<=> operator marks the default 284 value .N<This isn't an assignment, it's only a reuse of the C<=> symbol285 in a different context.> The parameter takes the default value only if286 the call doesn't pass an argument for that parameter.320 valueN<This isn't an assignment, it's only a reuse of the C<=> symbol 321 in a different context.>. The parameter takes the default value only 322 if the call doesn't pass an argument for that parameter. 287 323 288 324 sub default_vals ($required, ?$optional = 5) {...} 325 326 Default values are only used with optional parameters. This should make 327 sense because required positional values are always required, and so 328 they always have a value passed. 289 329 290 330 =head2 Placeholder Variables … … 301 341 variables with a caret after the sigil--C<$^name>, C<@^name>, 302 342 C<%^name>, or C<&^name>--within the subroutine's block, and the 303 arguments passed into the subroutine are bound to them. 343 arguments passed into the subroutine are bound to them. 304 344 305 345 @sorted = sort { $^a <=> $^b } @array; … … 348 388 349 389 X<arguments> 350 X<arguments;passing> 390 X<arguments;passing> 351 391 The standard way of passing arguments is by position. The first 352 392 argument passed in goes to the first parameter, the second to the … … 386 426 To get the Perl 5-style behavior where the elements of an array (or 387 427 the pairs of a hash) flatten out into the parameter list, use the 388 flattening operator in the call to the subroutine. Here, C<$first>389 binds to C<@array[0]> and C<$second> binds to C<@array[1]>:428 flattening operator C<*> in the call to the subroutine. Here, 429 C<$first> binds to C<@array[0]> and C<$second> binds to C<@array[1]>: 390 430 391 431 sub flat ($first, $second) {...} … … 414 454 Positional arguments, if there are any, always go first. Named 415 455 arguments go after any positional arguments. Variadic arguments always 416 go at the end of the list. 456 go at the end of the list. 417 457 418 458 order($positional, named => 1, 'va', 'ri', 'ad', 'ic'); … … 539 579 C<My::Module> declares a subroutine C<firstsub> and calls it from within 540 580 C<secondsub>. C<Other::Module> declares a subroutine C<thirdsub> that 541 calls C<firstsub> using its fully qualified name. 581 calls C<firstsub> using its fully qualified name. 542 582 543 583 =head2 Lexically Scoped Subroutines … … 561 601 } 562 602 563 # dine($arthur, "Nutri-Matic"); # error603 dine($arthur, "Nutri-Matic"); # error - not in scope! 564 604 565 605 The first call to the lexically scoped C<dine> is fine, but the second … … 609 649 they have to get the equivalent of a name somewhere, whether they're 610 650 assigned to a variable, passed as a parameter, or aliased to another 611 subroutine. 651 subroutine. 612 652 613 653 $make_tea = sub ($tealeaves, ?$sugar, ?$milk) {...} … … 645 685 X<subroutines;multi> 646 686 You can define multiple routines with the same name but different 647 signatures . These are known as "multisubs" and defined with the648 C<multi> keyword before C<sub>. They're useful if you want a routine 649 that can handle different types of arguments in different ways, but 650 still appear as a single subroutine to the user. For example, you 651 might define an C<add> multisub with different behavior for integers, 652 f loats, and certain types of numeric objects:687 signatures in the same scope. These are known as "multisubs" and 688 defined with the C<multi> keyword before C<sub>. They're useful if 689 you want a routine that can handle different types of arguments in 690 different ways, but still appear as a single subroutine to the user. 691 For example, you might define an C<add> multisub with different behavior 692 for integers, floats, and certain types of numeric objects: 653 693 654 694 multi sub add (Int $first, Int $second) {...} … … 667 707 parameters and the rest of the signature with a semi-colon: 668 708 669 multi sub add (Int $first, Int $second :Int $third) {...}709 multi sub add (Int $first, Int $second; Int $third) {...} 670 710 671 711 This version of C<add> will dispatch based on the types of the first 672 712 two arguments passed in, and ignore the type of the third. 673 674 713 675 714 =head1 Curried Subroutines … … 798 837 routine executes as soon as it's parsed. The parser substitutes the 799 838 return value from the macro into the parse tree in place of the macro 800 call. If a macro returns C<undef>, it makes no entry in the parse 801 tree. So, the macro C<disappear> takes a single string argument and 802 returns C<undef>. Any call to C<disappear> is replaced at compile time 803 with nothing, just as if it were commented out. 839 callN<This is an important point, because Perl 6's macros are not the 840 same plain-text-replacement mechanism that has become common place to 841 C and C++ programmers. Perl 6's macros actually manipulate the parse 842 tree and have all the power of the full Perl 6 language.>. If a macro 843 returns C<undef>, it makes no entry in the parse tree. So, the macro 844 C<disappear> takes a single string argument and returns C<undef>. 845 Any call to C<disappear> is replaced at compile time with nothing, 846 just as if it were commented out. 804 847 805 848 macro disappear (Str $thinair) { … … 811 854 disappear("Some text you'll never see"); 812 855 813 If a macro returns a string, the string is parsed as Perl source code, 814 and the resulting parse tree replaces the macro call. So, anywhere the 815 macro C<twice> is called, it is replaced at compile time by a C<for> 816 modifier. 856 This technique might seem like a nice way to add custom comment operators, 857 but as we will see in A<CHP-7> Chapter 7: "Grammars and Rules", there are 858 better ways to add custom commenting operatorsN<custom operators of all 859 types, in fact>. If a macro returns a string, the string is parsed as 860 Perl source code, and the resulting parse tree replaces the macro call. 861 So, anywhere the macro C<twice> is called, it is replaced at compile time 862 by a C<for> modifier. 817 863 818 864 macro twice { … … 826 872 If a macro returns a block, that block is parsed as a closure, and the 827 873 resulting parse tree replaces the macro call. So, when the 828 C<reverse_numeric> macro is called, the parser substitutes the block 874 C<reverse_numeric> macro is called, the parser substitutes the block 829 875 C<< { $^b <=> $^a } >> in place of the call. 830 876 … … 856 902 857 903 macro funky (Str $whatever) 858 is parsed (/:w like (\w+), you know/) 904 is parsed (/:w like (\w+), you know/) 859 905 { 860 906 return { plain($whatever); };
