in reply to Error: Can't use string as a hash ref

If you change
Handler => MyHandler
to
Handler => MyHandler->new
the code runs again. I do not use SAX, so I am not sure it is the right way.

Replies are listed 'Best First'.
Re^2: Error: Can't use string as a hash ref
by Nocturnus (Scribe) on Apr 22, 2012 at 07:15 UTC

    Thank you very much for pointing me to the right direction!

    I probably would never have tried it that way since nearly all examples I have found are like my original code.

    Just one comment which might be interesting for others as well:

    At first, since I had not implemented a sub "new" in MyHandler, I was wondering why your solution was working at all. Then I understood that probably the "constructor" ("new") of the base class was called instead which explains why there was no compilation error.

    Nevertheless, I was still unsure what was going on behind the scenes. If really "new" from the base class would have been called, I would have expected that an instance of the base class would have been returned. But this is not the case since "start_document" (from MyHandler) has been executed instead of "start_document" from the base class (the latter would not have output anything to the console).

    So, for me, there was a contradiction. I really would like to understand this, but currently, I don't have the time to dig into the details. Instead, I have done it a way I am considering safe (mainly by copying and pasting examples from the web which made sense IMHO). I just added the constructor to MyHandler like that:

    ... package MyHandler; use base qw(XML::SAX::Base); sub new { my $s_Class = shift(); return (bless ({ }, $s_Class)); } ...

    That way, "new" for sure returns the right type (object reference), and I don't have to worry about possible side effects or unexpected behavior.

    Thank you very much again,

    Nocturnus

      I would have expected that an instance of the base class would have been returned.
      You should read more on Object Oriented Programming. This is not how inheritance works. Try this:
      { package MyBase; sub new { my $class = shift; warn "Constructing $class\n"; bless {}, $class; } } { package MyChild; use base 'MyBase'; } package main; use feature 'say'; my $p = MyBase->new; my $ch = MyChild->new; say for $p, $ch;

      Updated: MyBase quoted in "use base".

        Thank you very much for the explanation. I think I've got it now.

        Regards,

        Nocturnus