如何同时分配多个 Moose 属性?
我逐渐对一些代码进行了 Moose 化,这些代码从分隔的管道中读取行,分割每个行并使用哈希切片分配将它们添加到哈希中。
我已将哈希转换为 Moose 类,但现在我不知道如何快速将文件中的字段分配给该类的属性(如果有的话)。
我知道我可以很容易地做到:
my $line = get_line_from_file;
my @fields = split /\|/, $line;
my $record = My::Record->new;
$record->attr1($fields[0]);
...
但我希望有一个快速的衬里一次性分配所有属性,有点类似于:
my $line = get_line_from_file;
my %records;
@records{@field_names} = split /\|/, $line;
我读过有关强制的内容,但据我所知,这不是我想要的。
是否可以?
谢谢
I'm gradually Moose-ifying some code that reads lines from a pipe delimited, splits each and assigns adds them to a hash using a hash slice.
I've turned the hash into a Moose class but now I have no idea how to quickly assign the fields from the file to the attributes of the class (if at all).
I know I can quite easily just do:
my $line = get_line_from_file;
my @fields = split /\|/, $line;
my $record = My::Record->new;
$record->attr1($fields[0]);
...
but I was hoping for a quick one liner to assign all the attributes in one go, somewhat akin to:
my $line = get_line_from_file;
my %records;
@records{@field_names} = split /\|/, $line;
I've read about coercion but from what I can tell it's not what I'm after.
Is it possible?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
List::MoreUtils
模块中的zip
将属性传递给构造函数:Pass the attributes to the constructor using
zip
from theList::MoreUtils
module:我认为您使用哈希切片方法走在正确的轨道上。我会做类似的事情:
你也许能够想出一个粗糙的地图解决方案来实现同样的目标,但我会在可读性方面犯错误。
I think you're on the right track with the hash slice approach. I'd do something like:
You might be able to come up with a gnarly
map
solution to achieve the same thing, but I'd err on the side of readability here.如果对象尚未构造,您可以简单地将所有键和值传递到构造函数中:
或者如果对象已经创建并且您想要添加一些新字段:
If the object is not constructed yet, you can simply pass all the keys and values into the constructor:
or if the object is already created and you want to add some new fields: