Moose ArrayRef 属性作为数组返回
我有一个 Moose 类,其属性是 ArrayRef (只读),并由对象在内部进行操作。但是当有人调用访问器方法时,我希望它返回一个数组(或列表)而不是引用。这不仅会减少类的用户必须执行的取消引用量,而且意味着他们不会意外地篡改我的对象正在使用的相同引用。
那么最好的方法是什么?某种强制?
I have a Moose class with an attribute that is an ArrayRef (read-only) and is manipulated internally by the object. But when someone calls the accessor method I want it to return an Array (or list) not a reference. Not only would this cut down on the amount of dereferencing that the user of the class has to do, but it will mean they can't accidentally tamper with the same ref that my object is using.
So what's the best way to do this? Some sort of coercion?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 Moose::Meta::Attribute:: Native::Trait::Array 和委托,例如
(通过 #moose 上的 doy)
auto_deref
具有不良行为,如果您在标量上下文中调用访问器,仍然返回引用。Use Moose::Meta::Attribute::Native::Trait::Array and delegation, e.g.
(via doy on #moose)
auto_deref
has the undesirable behavior of still returning a reference if you call the accessor in scalar context.虽然您可以使用
auto-deref
,但Moose::Manual::BestPractices 表示这不是最好的方法,您应该考虑使用 Moose::Meta::Attribute::Native 来完成该功能。While you can use
auto-deref
, Moose::Manual::BestPractices says that this isn't the best way to do it, and that you should instead consider using Moose::Meta::Attribute::Native to accomplish that functionality.使用 auto_deref 选项:
请注意,有时您不会使用 reader 方法时返回一个数组,具体取决于表达式的标量或列表上下文。不久前,我遇到了一种情况,我必须显式地将数组上下文引入表达式才能使取消引用起作用。如果我能找到它,我将添加一个示例。
Use the auto_deref option:
Note that sometimes you won't get an array back when using the reader method, depending on the scalar or list context of the expression. A while ago I ran into a situation where I had to explicitly bring array context to the expression in order to get the dereferencing to work.. I'll add an example if I can find it.