Many consider Perl prototypes to be a failed experiment. I think the intention was that prototypes would allow you to write subroutines that behaved like buildins. Except that it never worked. It's still not possible to prototype something like print. Prototypes often don't do what you want, and do what you don't want. For instance, it seems to be possible to prototype a function that takes exactly two arguments:
sub foo($$);
However, if you write:
sub foo($$);
sub bar;
bar "arg1", foo "arg2", "arg3", "arg4";
it won't be parsed as:
bar("arg1", foo("arg2", "arg3"), "arg4");
And neither is this going to do what you expect:
sub foo ($$);
my @args = ("arg1", "arg2");
foo @args;
I do use prototypes, but only to tell the parser how I want functions to be parsed. The cases I use:
sub foo(); # Sub takes no arguments.
sub foo($); # Sub takes one argument.
sub foo(&@); # First argument is a block.
sub foo(\@@); # First argument will be reffed.
The first two are useful to prevent functions to gobble up all arguments, for instance:
sub bar;
sub foo($);
bar "arg1", foo "arg2", "arg3";
is parsed as bar("arg1", foo("arg2"), "arg3"). This trick only works with empty prototypes, and ($) prototypes. The & in a prototype (as first character in a prototype) means that the argument is a subroutine but the word "sub" may be omitted. This would allow you to mimic (block) map and grep. \@ makes it possible to mimic push (and there's \% as well, to mimic keys).
But you can't prototype print, with its optional first argument. Or eval, which takes a block or a scalar as first argument. Or select which takes 2 or 4 arguments. Nor can you (yet) use a prototype to mimic the many functions that take an optional single argument, while defaulting to $_ if no argument is given. split, whose first argument is a string or a regex can't be prototyped either.
|