LoginSignup
3
3

More than 5 years have passed since last update.

Reactive Programmingの勉強をPerlではじめる (1)

Last updated at Posted at 2015-08-23

Reactiveってなに?って方は Reactive とは何か? を読んでください。

この記事ではちょっとずつ加筆修正しながらReactive Programmingを試していきたいと思います。
一緒に勉強して下さる方とかいたら Twitter::PitneS まで連絡下さるとうれしーです。

1. Ping, Pong

emit

参考資料2では次のようなソースがExample Codeとして記載されています。

Echoer.pm
package Echoer;

use Moose;
extends 'Reflex::Base';

sub ping {
    my ($self, $args) = @_;
    print "echoer was pinged!\n";
    $self->emit( -name => "pong" );
}

Mooseは、完全なオブジェクトシステムをPerl5に提供するライブラリです。Mooseで使用されるAttributesはこちらで参照できます。
一例を挙げると、例えば型はVar is a Strのようにisaを用いて定義され、属性はVar is read-onlyのようにisを用いて設定されます。
また、extendsはよくあるオブジェクトの継承に利用される関数です。Mooseをuseしているので使えています。

Example_of_Moose
  package User;
  use Moose;
  extends 'Person';
  has 'password' => (
      is  => 'rw',
      isa => 'Str',
  );

Example CodeによるとEchoerはping関数を持ち、そこでは Reflex::Role::Reactiveで定義されるemit関数が使われています。
emitとは何か。ここによれば、watch() allows one object (the watcher) to register interest in events emitted by another.とあり、watcherによって観測されるeventの一種だということが分かります。

react

ところでPinger側のExample Codeでは、型がEchoerのデフォルト値sub { Echoer->new() }の読み書き可能な(hasではなくwatchesを用いているため)echoerを宣言しています。

Pinger.pm
package Pinger;

use Moose;
extends 'Reflex::Base';

use Reflex::Trait::Watched qw(watches);

watches echoer => (
    isa => 'Echoer',
    default => sub { Echoer->new() },
);

sub BUILD {
    my $self = shift;
    $self->echoer->ping;
}

sub on_echoer_pong {
    my $self = shift;
    print "Pinger got echoer's pong!\n";
    $self->echoer->ping();
}

宣言されたechoerはPingerのBUILD時に呼ばれ、結果としてpingが実行されます。
その場合、冒頭でも記したようにpingはpongをemitするため、Pingerのon_(オブジェクト名)_(当該オブジェクトがemitしたイベント名) { ... }が呼び出されることになります。

結果として、

PitneS$ perl -e "use Pinger; use Echoer; Pinger->new()->run_all();"
echoer was pinged!
Pinger got echoer's pong!
echoer was pinged!
Pinger got echoer's pong!
echoer was pinged!
Pinger got echoer's pong!
echoer was pinged!
...

という結果が得られます。なお run_all();こちらによれば run_all(): Run all active Reflex objects until they destruct. 、つまり生成したReflexオブジェクトを実行する関数です。

参考資料

URL

  1. Reactive とは何か? 18Aug2015, by @okapies.
  2. Reflex - Class library for flexible, reactive programs. 21Apr2013, by Rocco Caputo.
  3. Moose - A postmodern object system for Perl 5 2006, by Infinity Interactive, Inc.
  4. Moose::Manual - Mooseとはなにか、どうやって使うのか 2008-2009 by Infinity Interactive, Inc.
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3