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
#!/usr/bin/env perl use strict; use warnings; use 5.10.0; { package Foo; use Moo; has 'attr1' => ( is => 'rw' ); has 'attr2' => ( is => 'rw' ); sub hallo { my( $self, $str, $ref ) = @_; return sprintf '%s : %s - %s', $str, $self->attr1, $self->attr2; } } my $foo = Foo->new( { attr1 => 8, attr2 => 'c' } ); say $foo->hallo( 'welt', { attr1 => 9, attr2 => 'd' } );
1 2 3 4
for my $key ( keys %{ $ref || {} } ) { my $sub = $self->can( $key ); eval{ $self->$sub( $ref->{$key} ) } if $sub; }
1 2 3 4 5 6 7 8 9 10
sub hallo { my( $self, $str, $ref ) = @_; $self->attr1( $ref->{attr1} ) if exists $ref->{attr1}; $self->attr2( $ref->{attr2} ) if exists $ref->{attr2}; return sprintf '%s : %s - %s', $str, $self->attr1, $self->attr2; } }
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;
1
2
3
4
5
6
7
Welt : 8 - c
Welt : 9 - d
$VAR1 = bless( {
'att1' => 9,
'att2' => 'd',
'mod_att' => sub { "DUMMY" }
}, 'main' );