Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: (bbfu) (prototype misconception) Re(2): Declaring Subroutines (predeclare, catch errs at compiletime?)

by hdp (Beadle)
on Apr 25, 2001 at 05:58 UTC ( [id://75353] : note . print w/replies, xml ) Need Help??


in reply to (bbfu) (prototype misconception) Re(2): Declaring Subroutines (predeclare, catch errs at compiletime?)
in thread Declaring Subroutines

"Basically, prototypes are not for catching errors at compile time. Rather, they're for changing the precedence of the subroutine calls."
% perl -le 'sub f ($) { print @_ } f(1, 2)' Too many arguments for main::f at -e line 1, at end of line Execution of -e aborted due to compilation errors. % perl -le 'sub f ($) { print @_ } f()' Not enough arguments for main::f at -e line 1, at end of line Execution of -e aborted due to compilation errors.

Prototypes have been catching errors of this sort since 5.002.

hdp.

  • Comment on Re: (bbfu) (prototype misconception) Re(2): Declaring Subroutines (predeclare, catch errs at compiletime?)
  • Download Code

Replies are listed 'Best First'.
Re (tilly) 4: Declaring Subroutines (predeclare, catch errs at compiletime?)
by tilly (Archbishop) on Apr 25, 2001 at 17:52 UTC
    In my experience prototypes cause more errors than they solve, plus accidental interpretation of an array as a scalar is a far more confusing error than getting the number of arguments wrong.

    Besides which, when you have to teach someone Perl it is far easier to not use prototypes (and tell them that not using them is part of a coding standard if they do discover them) than it is to explain what they are and (if they are coming from C) explain why they don't really do what you might expect from something called a prototype.

(bbfu) (further prototype misconception) Re(4): Declaring Subroutines (predeclare, catch errs at compiletime?)
by bbfu (Curate) on Apr 25, 2001 at 06:59 UTC

    Well, ok. I suppose I should've said that, while prototypes will catch some errors at compile time, that is not what they were really intended for. Plus, they can (and will) introduce other, less obvious errors at run time. The article explains it much better than I could; if you have not already read it, I suggest you do.

    Regardless, my point was that you should be sure that you understand what prototypes really do before using them and that some simple "error checking" is not a good reason to use them (even if you do understand them).

    Prototypes can be useful in a few (very few) situations. Unfortunately, their use, especially for the wrong reasons, can also be dangerous.

    bbfu
    Seasons don't fear The Reaper.
    Nor do the wind, the sun, and the rain.
    We can be like they are.