in reply to Re: XML::Parser Weirdness
in thread XML::Parser Weirdness

I wasn't sure how to prototype something I was going to be passing by reference with&handler_start. Is it better to avoid prototyping here, or to prototype like this: sub handler_start; instead?

Thanks!

Replies are listed 'Best First'.
Perl Prototypes (was Re: XML::Parser Weirdness)
by grantm (Parson) on Jul 10, 2003 at 10:23 UTC
    Is it better to avoid prototyping here, or to prototype like...

    It's best to avoid prototyping altogether unless you know what it does. In C a prototype tells the compiler, as well as anyone reading the code, what type of arguments a function expects and what type of value it returns. That is not what Perl prototypes do and not what they're for.

    Consider Perl's built-in 'push' function. It takes an array followed by a list of one or more scalars:

    push ARRAY, LIST

    If you tried to write a similar function yourself in Perl you might start it like this:

    sub my_push { my(@array, @list) = @_; ...

    But that's not going to work for two reasons:

    1. @array is now a copy of the array that was passed to your function, so nothing you do to it will affect the original
    2. the arguments to my_push have been flattened into a single array so all the values end up in @array and @list ends up empty

    Perl prototypes let you write subroutines that work the same way Perl functions do. They let you implicitly take a reference to the calling arguments and they let you avoid the problem of everything being flattened to a single array. A working version of my_push might start like this:

    sub my_push (\@@) { my($array_ref, @list) = @_; ...

    There are lots of subtleties with using prototypes (eg: in our example we do want the list of scalars to be flattened - hence no leading backslash on the second '@') so if you don't know what you're doing you can create problems that are hard to debug.

    It's unfortunate that this facility in Perl is called 'prototypes' when it really means an entirely different thing than what you might be familiar with that term meaning.

    Short story: if you're not trying to write subroutines that work like Perl's built-in functions then don't use prototypes at all.

      I didn't realize how different C & Perl prototypes were. Thanks for the explanation!