I have a substantial program written with HTML::Parser, and we decided to trap errors 
to write them to an xml file.  So I wrote a module containing a $SIG{__DIE__} handler 
to do this redirection.

I'm having a couple of problems.

1) I want to get the package name in which the error occurs, and for this I'm using 
($package) = caller(1).  (The package with my die handler is caller(0).)  
Unfortunately, when the die is caught in an HTML::Parser handler, I'm getting 
"HTML::Parser" as the package, instead of the package which contains the handler.  A 
program illustrating this problem is attached below.

2) Sometimes when a die occurs in a handler, I don't get the die message, I get an 
empty string instead.  I'm trying to come up with a simple program which illustrates 
this problem, but I haven't been successful so far.

Here's my program illustrating problem (1).  It expects a file named 
sig_die_test.html, which can be any html file with a <title> tag in it:

#!/usr/bin/perl -w
package diehandler;

sub setup {
   my ($fname) = @_;

   $SIG{__DIE__} = sub {
      die @_ if $^S; # don't use this handler if called within eval
      my $err = $_[0]; chomp $err;

      my $diehandler = diehandler->new($fname);
      $diehandler->report_error($err);
      return 1;

   };
}

sub new {
   my ($class, $fname) = @_;
   my $self = bless {_fname => $fname}, $class;
   return $self;
}

sub report_error {
   my ($self, $err) = @_;
   my ($package) = caller(1); # should be parserdie, reports HTML::Parser
   print "Fatal error parsing " . $self->{_fname} . " in $package: $err\n";
}

###############################################################################

package parserdie;

use HTML::Parser;
use strict;

diehandler::setup("sig_die_test.html");

my $parser = HTML::Parser->new(api_version => 3,
                            start_h => [\&start, "tagname"]);

$parser->parse_file("sig_die_test.html");

sub start {
   my ($tagname) = @_;

   if ($tagname eq "title") {
      die "I hate title tags!\n";
   }
}

###############################################################################



Reply via email to