abubacker has asked for the wisdom of the Perl Monks concerning the following question:
Can any one tell me what is the use of function prototypes in Perl . I know that is optional but I want to know that whether it has any use.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: USAGE OF Prototype
by dHarry (Abbot) on Aug 06, 2009 at 13:49 UTC | |
It doesn't do what you think it does (Perl doesn't have named formal parameters, and yes I read your mind). Prototypes cause trouble and are best avoided. But to answer your question, prototypes allow you to change Perls usual argument-passing mechanism. It is an understatement to say this is tricky. If you want to validate arguments passed in you might want to take a look at Params::Validate. Also the PBP has a few good tips on how to use subs. HTH | [reply] |
|
Re: USAGE OF Prototype
by si_lence (Deacon) on Aug 06, 2009 at 13:35 UTC | |
cheers, si_lence | [reply] |
|
Re: USAGE OF Prototype
by Unforgiven (Hermit) on Aug 06, 2009 at 13:38 UTC | |
This page on perldoc.perl.org may be of use to read through. | [reply] |
|
Re: USAGE OF Prototype
by ELISHEVA (Prior) on Aug 07, 2009 at 07:41 UTC | |
The only really good use for prototypes is the creation of syntactic sugar. Perl prototypes can let you do neat things like write your own custom grep function that you can call like this: grepilicious {...} @someArrayPrototypes can also provide limited parameter checking but there are a lot of gotchas involved. In fact, so many that the standard advice is not to use them that way. Here are two: Protypes can also interfere with good programming practice if you aren't careful. Passing @_ is a good way to cleanly define two almost alike subroutines. It is a lot less prone to typos than extracting all the parameters and then passing them one by one to a subroutine that takes the same parameters:
But if you define foo($;$) with a prototype, the above code won't work. Instead of passing the parameters, you'll pass the size of @_, which is not at all what you wanted. Best, beth | [reply] [d/l] [select] |
|
Re: USAGE OF Prototype
by biohisham (Priest) on Aug 06, 2009 at 14:02 UTC | |
(updated) prototypes are flexible, you can also indicate to a function whether a certain prototype is optional and you can include references to hashes in there.this function expects 2 scalar arguments and one optional argument after the ";"...so bear in mind that not all of this is irrelevant and there will come a time when you'd better use a prototype in a function definition than pass it over.
Excellence is an Endeavor of Persistence.
Chance Favors a Prepared Mind.
| [reply] [d/l] |
by SuicideJunkie (Vicar) on Aug 06, 2009 at 15:36 UTC | |
That sounds like more of a job for:
Append: Example of extensive parameter handling: Untested, and not self-contained. | [reply] [d/l] [select] |