class 内の変数の変更にウォッチャーをどのように設定するのか、コード例を提供できますか? さまざまな機能 ( Scalar::Watcher、Moo のトリガー属性) と OOP フレームワーク (Moo、Mojo::Base)を使用していくつかの方法で実行しようとしましたが、すべて失敗しました。
以下は、私のタスクをよりよく理解するための失敗したコードです。この例では、attr1 が変更されるたびに attr2 を更新する必要があります。
Mojo::Base と Scalar::Watcher の使用:
package Cat;
use Mojo::Base -base;
use Scalar::Watcher qw(when_modified);
use feature 'say';
has 'attr1' => 1;
has 'attr2' => 2;
has 'test' => sub { # "fake" attribute for getting access to $self
my $self = shift;
when_modified $self->attr1, sub { $self->attr2(3); say "meow" };
};
package main;
use Data::Dumper;
my $me = Cat->new;
$me->attr1;
warn Dumper $me;
say $me->attr1(3)->attr2; # attr2 is still 2, but must be 3
Moo とトリガーの使用:
package Cat;
use Moo;
use Scalar::Watcher qw(when_modified);
use feature 'say';
has 'attr1' => ( is => 'rw', default => 1, trigger => &update() );
has 'attr2' => ( is => 'rw', default => 1);
sub update {
my $self = shift;
when_modified $self->attr1, sub { $self->attr2(3); say "meow" }; # got error here: Can't call method "attr1" on an undefined value
};
package main;
use Data::Dumper;
my $me = Cat->new;
$me->attr1;
warn Dumper $me;
say $me->attr1(3)->attr2;
どんな提案でも大歓迎です。