首页 > 解决方案 > Perl 和契约式设计

问题描述

我知道 Perl 有 perldoc 用于类似于 Javadoc 等的文档目的。
但我想知道如何在 Perl 中记录一个特定的方法,即输入参数和输出参数的精确约定?
例如,输入应该是一个数组而不是一个标量等而不实际读取整个代码?

甚至可能吗?

标签: 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::ParametersType::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 );
}

推荐阅读