在设置之前,如何在驼鹿属性设置器中处理参数?

发布于 2025-01-20 07:18:01 字数 325 浏览 2 评论 0原文

我的驼鹿对象具有一个属性,该属性是字符串的阵列。我想通过仅传递单个字符串('string'),而不是单个字符串的arrayref(['code> ['String'''String' ])。

has 'my_list' => (
    is      => 'rw',
    isa     => 'ArrayRef[Str]',
);

解决这个问题的正确方法是什么?通过触发

我不确定是否在对象构造函数和属性设置程序中或仅在构造函数中都需要它。

My Moose object has an attribute that is an arrayref of strings. I want to make it possible to set it to a single-element list by passing only a single string ('string'), instead of an arrayref of a single string (['string']).

has 'my_list' => (
    is      => 'rw',
    isa     => 'ArrayRef[Str]',
);

What is the proper way of solving this? Through a trigger?

I'm not sure yet if I'll need this in both the object constructor and the attribute setter, or only in the constructor.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

乙白 2025-01-27 07:18:01

解决此问题的最佳方法是使用 类型强制< /a>(从另一种类型创建一种类型)。

请注意,强制转换为标准 Moose 类型不是一个好主意,因此我们还创建了一个子类型。

#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

package MyClass;

use Moose;
use Moose::Util::TypeConstraints; # defines 'subtype' and 'coerce'

# Our new subtype
subtype 'ArrayRefofStr',
  as 'ArrayRef[Str]';

# Define the coercion from a string to
# and array of strings
coerce 'ArrayRefofStr',
  from 'Str',
  via  { [ $_ ] };

has 'my_list' => (
    is      => 'rw',
    isa     => 'ArrayRefofStr', # Change to subtype
    coerce  => 1, # Turn on type coercion
);

package main;

my $obj1 = MyClass->new(my_list => ['foo']);
my $obj2 = MyClass->new(my_list =>  'bar' );

say $obj1->my_list->[0];
say $obj2->my_list->[0];

The best way to approach this is by using type coercion (creating one type from another).

Note, that it's a bad idea to coerce into standard Moose types, so we also create a subtype.

#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

package MyClass;

use Moose;
use Moose::Util::TypeConstraints; # defines 'subtype' and 'coerce'

# Our new subtype
subtype 'ArrayRefofStr',
  as 'ArrayRef[Str]';

# Define the coercion from a string to
# and array of strings
coerce 'ArrayRefofStr',
  from 'Str',
  via  { [ $_ ] };

has 'my_list' => (
    is      => 'rw',
    isa     => 'ArrayRefofStr', # Change to subtype
    coerce  => 1, # Turn on type coercion
);

package main;

my $obj1 = MyClass->new(my_list => ['foo']);
my $obj2 = MyClass->new(my_list =>  'bar' );

say $obj1->my_list->[0];
say $obj2->my_list->[0];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文