Mojoliciousでイベント駆動型プログラミングしてみた(その2)

 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
#!/usr/bin/env perl
use utf8;
use 5.012;
use Encode;

package Human;
use Mojo::Base 'Mojo::EventEmitter';

sub walk {
    my $self = shift;
    $self->emit(message => '歩いている。');
    $self->emit('walk');
    return;
}

sub get_poison {
    my $self = shift;
    $self->emit(message => '毒を受けた!');
    $self->on(walk => sub {
        $self->emit(message => "毒のダメージ!");
    });
}

sub cure_poison {
    my $self = shift;
    $self->emit(message => '毒が治った!');
    $self->unsubscribe('walk');
}

package main;

my $man = Human->new;
$man->on(message => sub {
    say Encode::encode_utf8($_[1]);
});

$man->walk for 1 ..2;
$man->get_poison;
$man->walk for 1 .. 2;
$man->cure_poison;
$man->walk for 1 .. 2;
 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
43
44
45
46
47
#!/usr/bin/env perl
use utf8;
use 5.012;
use Encode;

package Logger;
use Mojo::Base -base;

sub log {
    shift;
    say Encode::encode_utf8(join "\n", @_);
}

package Human;
use Mojo::Base -base;

has is_poison => 0;

sub walk {
    my $self = shift;
    my @results = ('歩いている。');
    if ($self->is_poison) {
        push @results, '毒のダメージ!';
    }
    return @results;
}

sub get_poison {
    shift->is_poison(1);
    return '毒を受けた!';
}

sub cure_poison {
    shift->is_poison(0);
    return '毒が治った!';
}

package main;

my $man = Human->new;
my $logger = Logger->new;

$logger->log($man->walk) for 1 .. 2;
$logger->log($man->get_poison);
$logger->log($man->walk) for 1 .. 2;
$logger->log($man->cure_poison);
$logger->log($man->walk) for 1 .. 2;
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy