Prototyping Functions

Problem

You want to use function prototypes so the compiler can check your argument types.

Solution

Perl has something of a prototype facility, but it isn’t what you’re thinking. Perl’s function prototypes are more like a context coercion used to write functions that behave like some of Perl’s built-ins, such as push and pop.

Discussion

Manually checking the validity of a function’s arguments can’t happen until run-time. If you make sure the function is declared before it is used, you can tickle the compiler into using a very limited form of prototype checking to help you here. Don’t confuse Perl’s function prototypes with those found in any other language. Perl prototypes serve only to emulate the behavior of built-in functions.

A Perl function prototype is zero or more spaces, backslashes, or type characters enclosed in parentheses after the subroutine definition or name. A backslashed type symbol means that the argument is passed by reference, and the argument in that position must start with that type character.

A prototype forces context on the arguments to the prototyped function call. This is done when Perl compiles your program, and in most cases this does not necessarily mean that Perl checks the number or type of the arguments to your function. If Perl sees func(3, 5) for a function prototyped as sub func ($), it will stop with a compile-time error. But if it sees func(@array) with the same prototype, it will merely put @array into scalar context instead ...

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.