如何更新作为 moose 属性的 Perl/Tk 小部件文本变量? [英] How to update a Perl/Tk widget textvariable that is a moose attribute?

查看:22
本文介绍了如何更新作为 moose 属性的 Perl/Tk 小部件文本变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Perl/Tk 中,可以为小部件定义文本变量.它是对保存值的一些标量的引用.有人向我展示了如何使用 Moose 属性强制将 Moose 属性用作文本变量(酷!).这是它的工作原理:

In Perl/Tk, one can define textvariables for widgets. It's a reference to some scalar that holds the value. Someone showed me how to use Moose attribute coercion to use Moose attributes as textvariable (cool!). This is how it works:

subtype 'TkRef' => as 'ScalarRef';
coerce 'TkRef', from 'Str', via { my $r = $_; return \$r };
has 'some_val' => (is => 'rw', isa => 'TkRef', coerce => 1, default => 'default value');

$mw->Entry(-textvariable => $self->some_val);
$mw->Label(-textvariable => $self->some_val); # will always Show what we type into the entry

但是,当我想为属性设置一个新值时,我必须像这样取消引用它:

However, when I want to set a new value for the attribute, I have to dereference it like this:

${$self->some_val} = 'blarg'; # dereference

简单地设置属性是行不通的,因为引用需要在对象的整个生命周期中保持不变(即属性值本身不能改变).

Simply setting the attribute won't work, as the reference needs to remain the same over the life of the object (that is, the attribute value itself cannot change).

有没有一种方法可以在不丢失使用 $self->some_val('blarg'); 设置属性的情况下使用漂亮的 Moose 属性强制功能?某种反向强制?

Is there a way to use the nice Moose attribute coerce feature without losing the possibility to set the attribute with $self->some_val('blarg'); ? Some sort of reverse-coercion?

推荐答案

将访问器设为私有,然后为访问器提供包装器.像这样:

Make the accessors private, and then provide a wrapper for the accessor. Something like this:

subtype 'TkRef', as 'ScalarRef';
coerce 'TkRef', from 'Str', via { my $r = $_; return \$r };

has _some_val => (
   is       => 'rw',
   isa      => 'TkRef',
   coerce   => 1,
   init_arg => 'some_val',
   default  => 'default value',
);

sub some_val {
   my $self = shift;
   if (@_ and not ref $_[0]) {
      ${$self->_some_val} = shift;
   }
   elsif (@_ and ref $_[0]) {
      ${$self->_some_val} = ${+shift};
   }
   $self->_some_val(@_);
}

这篇关于如何更新作为 moose 属性的 Perl/Tk 小部件文本变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆