Thread Moo Attribute überschreiben (7 answers)
Opened by Kuerbis at 2015-02-01 14:58

rosti
 2015-02-02 08:03
#179435 #179435
User since
2011-03-19
3472 Artikel
BenutzerIn
[Homepage]
user image
In herkömmlichen Perl würde das so aussehen (ich mache mal alles in der main zur Veranschaulichung):

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
29
30
31
use strict;
use warnings;
use 5.010;
use Data::Dumper;

# Modify Attribute
my $mod_att = sub{
    my $self = shift;
    my $ref = shift;
    $self->{att1} = $ref->{att1};
    $self->{att2} = $ref->{att2};
};

# vereinfachter Konstruktor
my $m = bless{
    mod_att => $mod_att,
    att1 => 8,
    att2 => 'c'
}, __PACKAGE__;

sub hallo{
    my $self = shift;
    my $str  = shift;
    my $ref  = shift;

    $self->{mod_att}->($self, $ref) if $ref;    

    return sprintf "%s : %s - %s", $str, $self->{att1}, $self->{att2};
}

say $m->hallo('Welt'), "\n", $m->hallo('Welt', {att1 => 9, att2 => 'd'}), "\n", Dumper $m;


Das gibt aus:

Code: (dl )
1
2
3
4
5
6
7
Welt : 8 - c
Welt : 9 - d
$VAR1 = bless( {
'att1' => 9,
'att2' => 'd',
'mod_att' => sub { "DUMMY" }
}, 'main' );


Stichwort für Moo: Codereferenzen als Attribute.

View full thread Moo Attribute überschreiben