使用定义的规则创建缩减 coderef 的库
是否有现有的 CPAN 库能够从基本测试的结构化输入创建 coderef,将传递的数据结构简化为真/假值?它需要能够将构造函数传递的属性映射到传递的数据结构的属性(即,在下面的示例中 [attribute => 'something']
映射到 $_-> ;{something}
在传递的标量上)并对它们执行测试。
我可以写一些东西,但我真的很惊讶我没有在 CPAN 上找到任何东西来处理它。有谁知道有图书馆可以做这种事情吗?
my @def = ( [ [ attribute => 'something' ], '>', 50 ],
'and',
[ [ attribute => 'something_else' ], 'eq', 'match' ],
);
my $coderef = Reducer->new(@def);
my @items = ( { something => 75,
something_else => 'match',
},
{ something => 20,
something_else => 'match',
},
{ something => 75,
something_else => 'no match',
},
{ something => 90,
something_else => 'match',
},
);
for my $item (@items) {
$coderef->($item) ? say 'true' : say 'false';
};
输出:
true
false
false
true
Is there an existing CPAN library that's able to create coderefs from a structured input of basic tests that reduce a passed data structure to a true/false value? it needs to be able to map passed attributes from the constructor onto the passed data structure's attributes (i.e., in the example below [attribute => 'something']
maps to $_->{something}
on the passed scalar) and perform tests against them.
I could write something, but I'm really surprised I'm not finding anything on CPAN to handle it. Does anyone know of a library to do this sort of thing?
my @def = ( [ [ attribute => 'something' ], '>', 50 ],
'and',
[ [ attribute => 'something_else' ], 'eq', 'match' ],
);
my $coderef = Reducer->new(@def);
my @items = ( { something => 75,
something_else => 'match',
},
{ something => 20,
something_else => 'match',
},
{ something => 75,
something_else => 'no match',
},
{ something => 90,
something_else => 'match',
},
);
for my $item (@items) {
$coderef->($item) ? say 'true' : say 'false';
};
outputs:
true
false
false
true
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
关于这个问题或者您的示例代码确实没有什么需要通过 coderef 来解决的;您更有可能找到一个将定义和要验证的项目作为参数的子例程。
我知道其中有几个;首先想到的是 Params::Validate::validate。
尽管定义结构与您的不同(验证规范的属性散列而不是数组等),但将您想要的接口包装起来是微不足道的。
Nothing about this problem or indeed your example code cries out to be solved by a coderef to me; you are more likely to find a subroutine that takes both the definition and item to validate as parameters.
I know there are several of those; the one that comes to mind first is Params::Validate::validate.
It would be trivial to wrap your desired interface around that, though the definition structure would differ from yours (a hash of attribute to validation spec instead of an array, etc).