是否有一个 Perl 模块可以在运行时动态地将 YAML 文件转换为 Moose 对象?
我一直在尝试找到一个 Perl 模块,可以将 YAML 文件转换为 moose 对象,而无需像使用 MooseX::YAML。有谁知道这样的模块(或脚本)?
I've been trying to find a Perl module that converts a YAML file into moose objects without having to pre-declare the structure as you seem to need to do when using MooseX::YAML. Does anyone know of such a module (or script)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您不想在 YAML 中执行任何特殊操作,则只需设置
对您的 Moose 类进行适当的强制转换,然后将加载的数据传递给
new()
。例如:然后,在某些 YAML 中:
然后,在某些代码中:
显然,如果没有对 Moose 类进行更多自定义,这不是可往返的——它只是用于构造对象。此外,您还需要知道根对象是什么类。
不过,对于许多简单的用途来说,这可能已经足够了。
If you don't want to do anything special in your YAML, you can just set up the
proper coercions for your Moose classes and then pass the loaded data to
new()
. For example:Then, in some YAML:
Then, in some code:
This isn't roundtrippable, obviously, without some more customization of your Moose classes -- it's just for constructing objects. Also, you need to know what classes the root objects are.
That's probably enough for a lot of simple uses, though.
不。
Moose 类、它们的属性以及属于它们的其他内容都附加有大量元数据。您无法从单个实例的数据推断出所有元数据。
我假设,给定一个
您期望的 yaml 文档,并返回响应对 foo 和 bar 方法的调用的对象,返回各自的值。但这些访问器应该如何表现呢?它们应该是简单的读取方法,还是也允许写入?他们应该针对任何类型的约束进行验证吗?等等。
如果您真正需要的只是使一些不受欢迎的数据结构像对象一样可访问,请查看
Data::Hive
,< code>Hash::AsObject 以及类似的模块。如果您确实想构建正确的 Moose 类,并且可以接受所涉及的猜测,或者碰巧在某处有必要的元数据,那么您可以使用元协议。
Don't.
Moose classes, their attributes, and whatever else belongs to them, have a lot of meta-data attached to them. You can't infer all of that meta-data from the data of a single instance.
I'm assuming, given a yaml document as
you'd expect and object back that responds to calls to a
foo
and abar
method, returning the respective values. But how should those accessors behave? Should they be simple reader-methods, or also allow writing? Should they validate against any kind of typeconstraint? etc.If all you really need is something that makes some unblessed data-structure accessible like an object, have a look at
Data::Hive
,Hash::AsObject
, and similar modules instead.If you really want to build proper Moose classes, and are either alright with the guesswork that'd be involved, or happen to have the necessary meta-data available somewhere, you can just use the meta-protocol.