develooper Front page | perl.cvs.parrot | Postings from January 2009

[svn:parrot] r35450 - trunk/docs/book

January 12, 2009 11:10
[svn:parrot] r35450 - trunk/docs/book
Message ID:
Author: Whiteknight
Date: Mon Jan 12 11:10:44 2009
New Revision: 35450


[Book] Update the section about methods, include some more details about syntax, the "self" keyword and the ":invocant" flag.

Modified: trunk/docs/book/ch04_pir_subroutines.pod
--- trunk/docs/book/ch04_pir_subroutines.pod	(original)
+++ trunk/docs/book/ch04_pir_subroutines.pod	Mon Jan 12 11:10:44 2009
@@ -520,7 +520,7 @@
-=head2 Methods
+=head2 Namespaces, Classes, and Methods
@@ -582,7 +582,7 @@
     $P1 = get_global ["Foo"], "MySubroutine"
     $P1()                           # invoke it
-=head3 Method Syntax
+=head3 Calling Methods
@@ -604,10 +604,38 @@
   .local string methname = "Foo"
   object.methname()               # Same as object."Foo"()
+  object."Foo"()                  # Same 
 The invocant can be a variable or register, and the method name can be
 a literal string, string variable, or method object PMC.
+=head3 Defining Methods
+Methods are defined like any other subroutine except with two major
+differences: They must be inside a namespace named after the class
+they are a part of, and they must use the C<:method> flag.
+  .namespace [ "MyClass"]
+  .sub "MyMethod" :method
+    ...
+Inside the method, the invocant object can be accessed using the C<self>
+keyword. C<self> isn't the only name you can call this value, however.
+You can also use the C<:invocant> flag to define a new name for the invocant
+  .sub "MyMethod" :method
+    $S0 = self                    # Already defined as "self"
+    say $S0
+  .end
+  .sub "MyMethod2" :method
+    .param pmc item :invocant     # "self" is now called "item"
+    $S0 = item
+    say $S0
+  .end
 This example defines two methods in the C<Foo> class. It calls one
 from the main body of the subroutine and the other from within the
 first method: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About