Ich würde auch entsprechende Accessor-methoden empfehlen:
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
32
33
34
35
36
37
38
39
40
41
42
#!/usr/bin/perl
use strict;
use warnings;
package Child;
use Moose;
has 'name' => (is => 'rw');
package Father;
use Moose;
has 'name' => (is => 'rw');
has 'children' => (is => 'rw', isa => 'ArrayRef');
use overload '+' => \&add,
'""' => \&to_s;
sub add {
my $self = shift;
push @{$self->{children}}, shift @_;
}
sub to_s {
my $self = shift;
my $sons = '';
$sons .= $_->name . ", " for @{$self->children};
$sons =~ s/\,\s(\w+)\,\s?$/ and $1/;
return $self->name . " and his sons: " . $sons;
}
package main;
no warnings;
my $son = Child->new(name => 'Jackson');
my $son2 = Child->new(name => 'Jim');
my $dad = Father->new(name => 'Jack');
$dad + $son;
$dad + $son2;
print $dad;
EDIT: Wenn die warnings stören, dann muss man auf overload verzichten.
EDIT2: Wenn schon overload, dann auch für: "".\n\n
<!--EDIT|Ronnie|1167752406-->