I'd like to expand on prototyping for a minute. Prototyping is putting a set of parentheses after the name of a sub to specify what types of variables it expects as arguments, and how many variables. Some examples:
#! /usr/bin/perl
use strict;
use warnings;
# sub without prototypes
# use unless you have a reason to prototype
sub foobar {
# do stuff;
}
# sub that expects one scalar
sub foobaz ($) {
# do stuff;
}
# sub that expects the first argument
# to be an array, the second to be a
# hash, and the third to be a scalar
sub foobarbaz (@, %, $) {
# do stuff;
}
There are probably 3 reasons you'd want to prototype:
- Speed: If you prototype a function, it becomes a candidate for inlining at compile time. Basically, whenever a function is called, there is some time taken to switch from the current function to the function, and then come back. This time can be eliminated by replacing the code that calls the function with the function's code itself. Before you go out and prototype all your functions for speed, know that this gain is very small, and unless you're doing some really heavy computer work, it's just going to cause confusion.
- Mimic strongly typed languages: Languages like Java and C believe that you should have very strict rules for variables -- you declare variables as a certain type and unless you explicitely declare a conversion they are treated as whatever you declare them as. Some people coming over from other languages can find Perls "Do what you mean" style hard to deal with at first (I personally did a lot of silly things when I first learned). You should not consider this to be a Good Reason.
- Try to prevent your users from doing something dumb: If your user doesn't read the POD / Manifest and does something dumb, they will get an error (assuming they use strict; and preferably also use warnings;). A lot of times, this can be really unperlish. (For instance, all functions in CGI.pm accept an unlimited number of arguments, and will display each one in turn).
I hope that helps,
Vautrin
Want to support the EFF and FSF by buying cool stuff? Click
here.