Content deleted Content added
Kadosknight (talk | contribs) →Syntax: PHP 7 construct name info |
→Perl 6: Minor corrections |
||
Line 549:
=== Perl 6 ===
With Perl 6, even more boilerplate can be left out, given that a default ''new'' method is inherited, attributes can be specified, as well as whether they can be set, reset, or are required. In addition, any extra constructor functionality can be included in a ''BUILD'' method which will get called to allow for custom initialization. A ''TWEAK'' method can be specified to post-process any attributes already (
<source lang="perl6">
class Person {
has Str $.first-name is required; # first name (a string) can only be set at
# construction time (the . means "public").
has Str $.last-name is required; # last name (a string) can only be set at
# construction time (a ! would mean "private").
has Int $.age is rw; # age (an integer) can be modified after
# during the object instantiation.
# Create a 'has-age' method which returns true if age has been set▼
# create a 'full-name' method which returns the person's full name.
method has-age { self.age.defined }▼
# this method can be accessed outside the class.
method full-name { $!first-name.tc ~ " " ~ $!last-name.tc }
# Check custom requirements▼
# this method is used only inside the class so it's declared as "private"
# by prepending its name with a !
▲ method !has-age { self.age.defined }
method TWEAK {
if
die "No person under
}
}
Line 572 ⟶ 579:
</source>
<source lang="perl6">
my $p0 = Person.new( first-name => 'Sam', last-name => 'Ashe', age => 42 );
my $
say $p1.full-name(); # OUTPUT: «Grace Hopper»
</source>
<source lang="perl6">
my $
my $p1 = Person.new( :first-name<Grace>, :last-name<Hopper> );
</source>
Line 588 ⟶ 597:
my $last-name = "Ashe";
my $age = 42;
my $
</source>
|