in reply to XML::Parser Weirdness

I don't think I found the reason for the occurring problem, but there is at least one odd part in your code:

sub handler_start() { print $_1, "\n"; }
                 ^^

With the () you prototype your subroutine. Thus, in doubt (e.g. calling the subroutine without brackets like print $x, $y, $z;), Perl will assume that your subroutine expects the specified kind of arguments — in your case no arguments.

I really don't think that it is the problem, but it is at least a bad habit as your subroutine really wants arguments.

Greetings,
Janek

Replies are listed 'Best First'.
Re: Re: XML::Parser Weirdness
by Anonymous Monk on Jul 09, 2003 at 17:51 UTC

    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!

      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!