in reply to The purpose of prototypes in perl subroutines
However, if you write:sub foo($$);
it won't be parsed as:sub foo($$); sub bar; bar "arg1", foo "arg2", "arg3", "arg4";
And neither is this going to do what you expect:bar("arg1", foo("arg2", "arg3"), "arg4");
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:
The first two are useful to prevent functions to gobble up all arguments, for instance: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.
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).sub bar; sub foo($); bar "arg1", foo "arg2", "arg3";
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.
|
---|