Perl and design by contract

Viewed 74

I know that Perl has perldoc for documentation purposes similar to Javadoc etc.
But I was wondering how would one document in Perl a specific method i.e. the exact contract of the input arguments and the output argument?
E.g. that the input should be e.g. an array instead of a scalar etc without actually reading the whole code?

Is it even possible?

2 Answers

If you browse some CPAN modules, you'll see several ways, but the most common would be something like

=heading1 FUNCTIONS

=over 4

=item my $hash_ref = foo( @bars )

Returns the hashed bars fooed.

I.e. each function shows its usage in the =item.

Some authors tend to write the documentation from the perspective of use cases rather than listing the functions. As we say in Perl, TIMTOWTWTD (There's more than one way to write the documentation).

A pattern I'm increasingly seeing in documentation is to document the arguments to a method or function and the return value(s) using Moose-like type constraints. An example of this would be in 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.

This kind of thing can be paired with a library like Function::Parameters or Type::Params to actually check the arguments passed to the function.

Using 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 );
}

Or using 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 );
}
Related