[Wellington-pm] Gratuitous use of Perl Prototypes

Enkidu enkidu at cliffp.com
Tue Nov 9 15:57:16 CST 2004


On Tue, 09 Nov 2004 22:04:34 +1100, you wrote:

>
>Enkidu wrote:
>
>> What about the following bit of horrible code?
>> 
>> #!/usr/bin/perl -w
>> 
>> my $var1 ;
>> my $var2 ;
>> sub blimey() ;
>> 
>> $var1 = "0" ;
>> blimey() ;
>> 
>> sub blimey() {
>> }
>> 
>> If you remove the "sub blimey() ;" line the compiler complains:
>> 
>> main::blimey() called too early to check prototype at test.pl line 7.
>> 
>> What's the reason and what can you do about it, short of putting all
>> the subs at the front of the code which looks horrible and makes it
>> hard to read!
>
>#!/usr/bin/perl -w
>
>my $var1 ;
>my $var2 ;
>$var1 = "0" ;
>blimey() ;
>
>sub blimey {
>}
>
>Works perfectly fine.  The problem with your code is that writing
>
>sub blimey() {
>}
>
>does invoke a prototype.  When you use prototypes, perl wants you to 
>declare the prototypes before you use them in the code.  If you put your 
>subs before the main body of your script, then this will fix the 
>problem.  Alternately you can just leave them out all together (which 
>might be wiser in this case)  Diagnostics says:
>
>     (W prototype) You've called a function that has a prototype before 
>the parser saw a definition or declaration for it, and Perl could not 
>check that the call conforms to the prototype. You need to either add an 
>early prototype declaration for the subroutine in question, or move the 
>subroutine definition ahead of the call to get proper prototype 
>checking. Alternatively, if you are certain that you're calling the 
>function correctly, you may put an ampersand before the name to avoid 
>the warning. See perlsub.
>
>
>To get a roughly similar effect as using a prototype for blimey, perhaps 
>you'd like to write:
>
>sub blimey {
>      die if @_;
>}
>
>A better option to prototypes for most people is to take advantage of 
>Params::Validate.
>
Arrgh! It's obvious once you know, isn't it?

Cheers,

Cliff



More information about the Wellington-pm mailing list