Thanks for the tip about eval. I didn't know Perl allows method names to be called via string variables. I thought an eval was needed. So my updated version of that eval line is:
$_[0]->$AUTOLOAD(@_);
As for prototypes, I tend to add them to method declarations as a form of minimal documentation to help me quickly understand what data types the method is expecting when I'm debugging code. (I also add more extensive POD and # comments, but the prototypes give me a quick snapshot.)
| [reply] [d/l] |
> As for prototypes, I tend to add them to method declarations as a form of minimal documentation to help me quickly understand what data types the method is expecting
Sorry but that's dangerous nonsense.
Using anything else than $ would be misleading hence even $ is redundant.
And even $ will make Class->method() act different to Class::method()
| [reply] [d/l] [select] |
My nethods are always intended to be used as methods ($obj->method(...)) and non-methods are always intended to be used as functions (class::function(...)). Method invocations rely on the first parameter being an object of the required type in order to function properly and to make sense. Yes, an end user can do whatever he/she wants (this is Perl, after all), but it won't work correctly in many cases, since additional methods and properties will likely be accessed in a method. For methods, my understanding is that $obj->method(...) and class::method($obj, ...) (assuming $obj is of type class) are functionally identical. Feel free to correct me if I am wrong.
In almost all cases, my methods and fuctions all have specific parameters that they are expecting (i.e., nothing, two scalars, a scalar followed by an array, a hash, etc.). So how is this dangerous?
I am aware that some Perl functions are flexible to accept multiple types of parameters and I have left off prototypes when I have created such functions, but I generally don't create functions like that. If I want to create such functions, then I usually use a hash/hashref as the last parameter and pull key/value pairs as needed.
| [reply] [d/l] [select] |
To elaborate on LanX’s comments:
Before using Perl prototypes you should study Tom Christiansen’s essay, “Far More than Everything You’ve Ever Wanted to Know about Prototypes in Perl, ” which is available within the Monastery here. To quote from the opening:
Nearly any programmer you encounter will, when asked what function prototypes are for, report the standard text-book answer that function prototypes are mainly used to catch usage errors at compile time in functions called with an unexpected type or number of parameters. This is what programmers are expecting of prototypes, and what Perl does not give them.
Think coercion rather than checking, and you’ll be closer to the mark. Read the article, then use prototypes only for those specialised cases where they’re really useful.
Hope that helps,
| [reply] |