1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
#!/usr/bin/env perl6 use v6; class MyClass { has $.length is rw; has $.height is rw; has $.color is rw; method my_method ( Array $list, Hash $opt? ) { if defined $opt { for %$opt.keys -> $key { when $key eq 'length' { $!length = $opt{$key}; } when $key eq 'height' { $!height = $opt{$key}; } when $key eq 'color' { $!color = $opt{$key}; } } } } } my $n = MyClass.new(); $n.my_method( [ 1, 2, 3 ], { length => 10, height => 6, color => 'green' }); say $n.perl;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class MyClass {
has $.length is rw;
has $.height is rw;
has $.color is rw;
method my_method ( Array $list, %opt? ) {
if %opt.defined {
for %opt.pairs {
self."{.key}"() = .value;
# self."{.key}"() := .value; Nee...
}
}
}
}
my $n = MyClass.new();
$n.my_method( [ 1, 2, 3 ], { length => 10, height => 6, color => 'green' });
say $n.perl;
QuoteKönnte man nicht mit can(...) (oder das perl6 äquivalent) prüfen, ob die Methode zum Wert existiert?
1
2
3
my $att = self.^attributes.first(*.name eq '$!length');
say $att.has_accessor;
say $att.readonly;
QuoteDas macht Inits einfacher und bei Vererbungen muss nicht jedes mal das new überschrieben werden
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#!/usr/bin/env perl6 use v6; class Term::Choose { has Str $.prompt is rw = 'Your Choice'; has Int @.mark is rw; method choose ( Array $orig_list, %opt? ) { for %opt.pairs { self."{.key}"() = .value; } } } my $n = Term::Choose.new(); $n.choose( [ 1 .. 10 ], { prompt => 'BBBBB', mark => [ 1 .. 4 ] } ); #Type check failed in assignment to @!mark; expected Int but got Array # in method choose at ... line 10 # in block <unit> at ... line 16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# allgemein %res = (%ha, %hb, %hc); # praktisches Beispiel # in Methoden Werte vorbelegen sub new{ my $class = shift; my %cfg = ( host => '', port => 80, http => '1.0', timeout => 10, @_); ... }
Guest janusCode (perl): (dl )%res = (%ha, %hb, %hc);
1
2
3
4
5
perl6 -e 'class C { has Int $.frobnifiability = 42; }; my C $c.=new; say $c.perl; $c.=clone(frobnifiability=>87); say $c.perl;'
# Output:
C.new(frobnifiability => 42)
C.new(frobnifiability => 87)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class MyOptions { has $.length = 10; has $.height; has @.names; } class MyClass { has MyOptions $.options = MyOptions.new; method modify(%changes) { $!options.=clone(|%changes); } } my MyClass $n.=new; say $n.perl; $n.modify({length => 42, names => ['Kai', 'Otto']}); say $n.perl;
1
2
MyClass.new(options => MyOptions.new(length => 10, height => Any, names => []))
MyClass.new(options => MyOptions.new(length => 42, height => Any, names => ["Kai", "Otto"]))