Thread Hash to Class-Attributes (21 answers)
Opened by Kuerbis at 2016-01-06 09:57

Kuerbis
 2016-01-06 09:57
#183407 #183407
User since
2011-03-20
936 Artikel
BenutzerIn
[default_avatar]
Hallo!
Code (perl): (dl )
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;


Geht die Zuweisung von $opt an die has-Variablen auch einfacher - so wie es z.B. mit Perl 5 geht:

Code (perl): (dl )
1
2
3
for my $key ( keys %$opt ) {
    $self->{$key} = $opt->{$key};
}

?

View full thread Hash to Class-Attributes