perl - Perl 和契约式设计
问题描述
我知道 Perl 有 perldoc 用于类似于 Javadoc 等的文档目的。
但我想知道如何在 Perl 中记录一个特定的方法,即输入参数和输出参数的精确约定?
例如,输入应该是一个数组而不是一个标量等而不实际读取整个代码?
甚至可能吗?
解决方案
我在文档中越来越多地看到的一种模式是使用类似 Moose 的类型约束来记录方法或函数的参数和返回值。这方面的一个例子是Data::Maker。
=item B<record_count> (I<Num>)
The number of records desired
=item B<data_sources> (I<HashRef>)
Used internally by Data::Maker. It's a hashref to store open file handles.
这种东西可以与Function::Parameters或Type::Params之类的库配对,以实际检查传递给函数的参数。
使用 Function::Parameters + Types::Standard:
=item C<< add($x, $y) >> : B<Num>, B<Num> -> B<Num>
Adds two numbers and returns the result.
=cut
fun add ( Num $x, Num $y ) {
return Num->( $x + $y );
}
或使用 Type::Params + Types::Standard:
=item C<< add($x, $y) >> : B<Num>, B<Num> -> B<Num>
Adds two numbers and returns the result.
=cut
sub add {
state $check = compile( Num, Num );
my ( $x, $y ) = &$check;
return Num->( $x + $y );
}
推荐阅读
- javascript - 如何让我的代码显示与所选国家相对应的标志?
- linux - 从 WSL2 内的 Docker 容器在 Windows 10 中启动 WebApp(没有 Docker for Windows)
- c# - 如何在下拉列表中选择项目
- javascript - React 共享状态:突出显示选择了哪个组件
- excel - 将 Google 表格转换为 Excel,然后作为电子邮件附件发送,但无法访问 XLXS 文件(未经授权的错误 401)
- scala - 如何在 Spark 中反转 OneHotEncoderEstimator 转换
- python - 我如何在python中将函数更改为一行
- python - 在python中为实例和类重载成员方法
- c# - 如何在传递的 PowerShell 参数上检查 null
- php - 登录后 Laravel 两个因素不起作用