Changeset 22302 for docs

Show
Ignore:
Timestamp:
09/20/08 23:52:33 (4 months ago)
Author:
Whiteknight
Message:

[Book] Add some clarificaitons about named parameters. Make some other small fixes here and there.

Files:
1 modified

Legend:

Unmodified
Added
Removed
  • docs/tutorial/ch05_subroutines.pod

    r22301 r22302  
    134134parameter to be passed in on every call isn't nearly flexible enough 
    135135for the average programmer, Perl 6 also allows optional parameters. 
    136 Each optional parameter is marked with a C<?> before the parameter 
    137 name: 
     136Optional parameters can be included or ignored without causing any 
     137errors. Each optional parameter is marked with a C<?> before the 
     138parameter name: 
    138139 
    139140  sub someopt ($required1, $required2, ?$optional1, ?$optional2) { 
     
    152153  someopt('req1', 'req2', 'opt1'); 
    153154  someopt('req1', 'req2'); 
     155 
     156Notice that it will still cause an error to pass too many or too few 
     157parameters in a list with optional parameters: 
     158 
     159  someopt('req1')                                  # WRONG! 
     160  someopt('req1', 'req2', 'opt1', 'opt2', 'extra') # WRONG! 
    154161 
    155162=head2 Named Parameters 
     
    181188parameters to find the positional parameter list. 
    182189 
     190If it makes more sense to do it, you can also use the alternate key 
     191syntax for passing parameters: 
     192 
     193 namedparams(1, :second(2), :third(3))      # Right 
     194 
     195Also, named parameters aren't positional, you can pass them in any 
     196orderN<Any order, so long as all the named parameters come after all 
     197the positional parameters, of course>. So, we can pass the second third 
     198and the third second: 
     199 
     200 namedparams(1, third => 3, second => 2) 
     201 
     202The point of having a name for your parameter is that you don't have to 
     203worry about the position of it. 
     204 
    183205=head2 Variadic Parameters 
    184206 
     
    193215C<*> before the parameter name will slurp up all the I<positional> 
    194216arguments that haven't already been bound to another positional 
    195 parameter.N<You may notice that this is the same symbol as the 
     217parameterN<You may notice that this is the same symbol as the 
    196218flattening/slurping operator in A<CHP-4-SECT-2.12>"Referencing (or 
    197 Not)" in Chapter 4.> So, the following call to C<transport> binds 
     219Not)" in Chapter 4.>. So, the following call to C<transport> binds 
    198220C<$arthur> to C<@names[0]>, and C<$ford> to C<@names[1]>: 
    199221 
     
    215237parameter. So, the following call to C<transport> binds the value of 
    216238the pair argument with the key C<'planet'> to the parameter 
    217 C<$planet>, but all the other pairs become part of the C<%flags> hash 
     239C<:$planet>, but all the other pairs become part of the C<%flags> hash 
    218240(more on this in A<CHP-5-SECT-3.1>"Named Argument Passing" later in 
    219241this chapter). 
    220242 
    221   sub transport ($planet, *%flags) {...} 
     243  sub transport (:$planet, *%flags) {...} 
    222244 
    223245  transport('name'    => 'Arthur', 
     
    227249 
    228250When 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. 
     251positional parameters must come after all positional parameters in 
     252the signature. They can either precede or follow the named parameters. 
     253Variadic named parameters only slurp up the named parameters that aren't 
     254bound already, so they can appear anywhere in the signatureN<anywhere 
     255after all the positionals, of course.>. 
    231256 
    232257=head2 Typed Parameters 
     
    238263Signature checking is sensitive not only to the number of arguments 
    239264and 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" in 
    241 Chapter 4 for more details on value and variable types.> The parameter 
     265symbol), but also to the value typeN<See A<CHP-4-SECT-1.8>"Types" in 
     266Chapter 4 for more details on value and variable types.>. The parameter 
    242267type is defined before the parameter name and before any symbols for 
    243268optional, named, or variadic parameters: 
     
    266291modified within the body of the subroutine. The C<is rw> property 
    267292marks a parameter as modifiable, so changes to the parameter within 
    268 the body of the sub modify the original variable passed in:  
     293the body of the sub modify the original variable passed in: 
    269294 
    270295  sub modifyparams ($first is rw, $second is rw) {...} 
     296 
     297Be careful about using the C<is rw> property unless it's necessary, 
     298inadvertent changes in a subroutine can change data values in the 
     299caller's scope that might not be expecting to be changed. At the 
     300very least, it's polite to document it when your subroutine is monkeying 
     301around in somebody else's scope. 
    271302 
    272303The C<is copy> property marks a parameter as pass-by-value, so the 
     
    274305 
    275306  sub passbyvalue ($first is copy, $second is copy) {...} 
    276    
     307 
     308This means that the parameter is not an alias for the value in the 
     309caller's scope, but it's not read-only either. It's a new variable, 
     310a copy of the original and free to be used however your subroutine 
     311sees fit. 
     312 
    277313=head2 Default Values for Parameters 
    278314 
     
    282318Sometimes it is useful to be able to define a default value for an 
    283319optional 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<=> symbol 
    285 in a different context.> The parameter takes the default value only if 
    286 the call doesn't pass an argument for that parameter. 
     320valueN<This isn't an assignment, it's only a reuse of the C<=> symbol 
     321in a different context.>. The parameter takes the default value only 
     322if the call doesn't pass an argument for that parameter. 
    287323 
    288324  sub default_vals ($required, ?$optional = 5) {...} 
     325 
     326Default values are only used with optional parameters. This should make 
     327sense because required positional values are always required, and so 
     328they always have a value passed. 
    289329 
    290330=head2 Placeholder Variables 
     
    301341variables with a caret after the sigil--C<$^name>, C<@^name>, 
    302342C<%^name>, or C<&^name>--within the subroutine's block, and the 
    303 arguments passed into the subroutine are bound to them.  
     343arguments passed into the subroutine are bound to them. 
    304344 
    305345  @sorted = sort { $^a <=> $^b } @array; 
     
    348388 
    349389X<arguments> 
    350 X<arguments;passing>  
     390X<arguments;passing> 
    351391The standard way of passing arguments is by position. The first 
    352392argument passed in goes to the first parameter, the second to the 
     
    386426To get the Perl 5-style behavior where the elements of an array (or 
    387427the 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]>: 
     428flattening operator C<*> in the call to the subroutine. Here, 
     429C<$first> binds to C<@array[0]> and C<$second> binds to C<@array[1]>: 
    390430 
    391431  sub flat ($first, $second) {...} 
     
    414454Positional arguments, if there are any, always go first. Named 
    415455arguments go after any positional arguments. Variadic arguments always 
    416 go at the end of the list.  
     456go at the end of the list. 
    417457 
    418458  order($positional, named => 1, 'va', 'ri', 'ad', 'ic'); 
     
    539579C<My::Module> declares a subroutine C<firstsub> and calls it from within 
    540580C<secondsub>. C<Other::Module> declares a subroutine C<thirdsub> that 
    541 calls C<firstsub> using its fully qualified name.  
     581calls C<firstsub> using its fully qualified name. 
    542582 
    543583=head2 Lexically Scoped Subroutines 
     
    561601  } 
    562602   
    563   # dine($arthur, "Nutri-Matic");  # error 
     603  dine($arthur, "Nutri-Matic");  # error - not in scope! 
    564604 
    565605The first call to the lexically scoped C<dine> is fine, but the second 
     
    609649they have to get the equivalent of a name somewhere, whether they're 
    610650assigned to a variable, passed as a parameter, or aliased to another 
    611 subroutine.  
     651subroutine. 
    612652 
    613653  $make_tea = sub ($tealeaves, ?$sugar, ?$milk) {...} 
     
    645685X<subroutines;multi> 
    646686You can define multiple routines with the same name but different 
    647 signatures. These are known as "multisubs" and defined with the 
    648 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 floats, and certain types of numeric objects: 
     687signatures in the same scope. These are known as "multisubs" and 
     688defined with the C<multi> keyword before C<sub>. They're useful if 
     689you want a routine that can handle different types of arguments in 
     690different ways, but still appear as a single subroutine to the user. 
     691For example, you might define an C<add> multisub with different behavior 
     692for integers, floats, and certain types of numeric objects: 
    653693 
    654694  multi sub add (Int $first, Int $second) {...} 
     
    667707parameters and the rest of the signature with a semi-colon: 
    668708 
    669   multi sub add (Int $first, Int $second: Int $third) {...} 
     709  multi sub add (Int $first, Int $second; Int $third) {...} 
    670710 
    671711This version of C<add> will dispatch based on the types of the first 
    672712two arguments passed in, and ignore the type of the third. 
    673  
    674713 
    675714=head1 Curried Subroutines 
     
    798837routine executes as soon as it's parsed. The parser substitutes the 
    799838return 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. 
     839callN<This is an important point, because Perl 6's macros are not the 
     840same plain-text-replacement mechanism that has become common place to 
     841C and C++ programmers. Perl 6's macros actually manipulate the parse 
     842tree and have all the power of the full Perl 6 language.>. If a macro 
     843returns C<undef>, it makes no entry in the parse tree. So, the macro 
     844C<disappear> takes a single string argument and returns C<undef>. 
     845Any call to C<disappear> is replaced at compile time with nothing, 
     846just as if it were commented out. 
    804847 
    805848  macro disappear (Str $thinair) { 
     
    811854  disappear("Some text you'll never see"); 
    812855 
    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. 
     856This technique might seem like a nice way to add custom comment operators, 
     857but as we will see in A<CHP-7> Chapter 7: "Grammars and Rules", there are 
     858better ways to add custom commenting operatorsN<custom operators of all 
     859types, in fact>. If a macro returns a string, the string is parsed as 
     860Perl source code, and the resulting parse tree replaces the macro call. 
     861So, anywhere the macro C<twice> is called, it is replaced at compile time 
     862by a C<for> modifier. 
    817863 
    818864  macro twice { 
     
    826872If a macro returns a block, that block is parsed as a closure, and the 
    827873resulting parse tree replaces the macro call. So, when the 
    828 C<reverse_numeric> macro is called, the parser substitutes the block  
     874C<reverse_numeric> macro is called, the parser substitutes the block 
    829875C<< { $^b <=> $^a } >> in place of the call. 
    830876 
     
    856902 
    857903   macro funky (Str $whatever)  
    858       is parsed (/:w like (\w+), you know/)  
     904      is parsed (/:w like (\w+), you know/) 
    859905  { 
    860906      return { plain($whatever); };