The thousand and one reasons to love Perl: [3] Subroutine parameters
There are many complaints brought forth against Perl. One of the few that is valid is the lack of a formal way to specify parameters when calling subroutines. It cannot be denied that this is a serious shortcoming, mainly because it prevents the compiler from checking the validity of your subroutine calls, which would catch errors early on, make debugging easier and save some coding effort on your part when checking parameters yourself. Since there is no official parameter passing convention, different styles have developed, which tends to confuse beginners, sometimes to the point that they stop using parameters and pass stuff around in global variables. Not good.
The upside of all this is that because you have to implement parameter passing yourself, you can do it according to your needs and liking, and the process becomes more flexible than in most other languages.
Simple (positional) parameters
sub foo{
my ($a, $b) = @_;
....
}
Optional parameters
Since there is no parameter checking, you can call a subroutine with less
than the full number of parameters. The subroutine will receive an undefined
value (that is: the well-defined value called undef) and can be
coded to act appropriately. So you can call above subroutine like
foo(123,345); foo(123); foo();
Variable parameter lists
The popular printf function takes a format string and a variable
list of parameters to print according to that format. If you wanted to
implemented it in Perl (which does not make sense, since Perl already has printf) you could write
sub printf{
my ($format, @list) = @_;
...
}
Named parameters
If you have a lot of parameters, some of them optional, it makes sense to
change from positional to named parameters. In Perl, this can be easily
implemented using hashes (which are a core language element).
sub bar{
my (%parameters) = @_;
my ($size, $offset) = @parameters{ qw [ size offset ] };
}
# call this function like
bar( offset => 100, size => 22 );
Named parameters with default values
Setting up default values for optional named parameters is simple,
just put the defaults in the parameter hash before the actual parameters, so
that they will be overwritten as needed:
sub bar{
my (%parameters) = ( size => 100, offset => 0, @_ );
my ($size, $offset) = @parameters{ qw [ size offset ] };
}
The future
Perl6 (which should ship within the decade, maybe even before Duke Nukem Forever) will have a syntax to formally specify parameters (if you want, it will be optional) that will support all of the mentioned features (plus parameter type checking, return types and other goodies), so that you will be able to write
sub bar
( int +$size=100 , int +$offset=0)
returns Array of Str { ... }



