我的 Moose 物件有一個屬性,它是字串的陣列參考。我希望通過僅傳遞單個字串 ( 'string') 而不是單個字串 () 的 arrayref來將其設定為單元素串列['string']。
has 'my_list' => (
is => 'rw',
isa => 'ArrayRef[Str]',
);
解決這個問題的正確方法是什么?通過一個trigger?
我還不確定是否在物件建構式和屬性設定器中都需要它,或者只在建構式中需要它。
uj5u.com熱心網友回復:
解決此問題的最佳方法是使用型別強制(從另一種型別創建一種型別)。
請注意,強制轉換為標準 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];
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/464660.html
