in reply to Extracting a hash reference from a string

Well, if you really died like this:
my %exception = (err => 42, str => 'My fault'); die \%exception;
then $@ would contain the hash reference. Since it seems to also include the text, I assume that you are throwing the error in a different way, stringifying the hash reference as you go along.

A better way to do this (if you want the error object to still work as a normal error message when not used as a hash ref) is to return a proper blessed object. That way you can use the overload.pm module to provide custom stringification, and also have access to your exception record.

Replies are listed 'Best First'.
Re: Re: Extracting a hash reference from a string
by Anonymous Monk on Mar 23, 2003 at 02:42 UTC
    The text 'Compilation failed...' is added by the require() function. It appears that require() adds this text to whatever is returned by the compilation process - in this case the hash ref from die().
      Yes, you are right. The require opcode always appends the string to $@, regardless if it is an object or not. Note that this will stringify your reference and then decrement the reference count to your hash. So don't try to access it through the pointer provided by the stringification (which would be a bad idea anyways).

      I guess this means you will have to use a different error mechanism if your required modules can fail in a variety of ways. You could adopt some convention of package variables, like this:

      eval { require MyModule } if (defined $MyModule::Error) { print "Couldn't load MyModule: ", $MyModule::Error->{message}, + "\n"; # ... }
      and in your MyModule.pm file:
      package MyModule; our $Error; # ... if ($some_error) { $Error = {err = 42, message => 'Sorry, my fault!'}; die; # or maybe just 'return 0;' }