[Wellington-pm] Gratuitous use of Perl Prototypes

Jacinta Richardson jarich at perltraining.com.au
Tue Nov 9 05:04:34 CST 2004


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.

All the best,

     Jacinta

-- 
    ("`-''-/").___..--''"`-._          |  Jacinta Richardson         |
     `6_ 6  )   `-.  (     ).`-.__.`)  |  Perl Training Australia    |
     (_Y_.)'  ._   )  `._ `. ``-..-'   |      +61 3 9354 6001        |
   _..`--'_..-_/  /--'_.' ,'           | contact at perltraining.com.au |
  (il),-''  (li),'  ((!.-'             |   www.perltraining.com.au   |




More information about the Wellington-pm mailing list