buff has asked for the wisdom of the Perl Monks concerning the following question:

Honourable Monks,

I'm having troubles using Storable for storing XML::LibXML object. It can store but it can't retrieve! What's more, perl crashes when I try to do it:

$ perl -MXML::LibXML -MData::Dumper -MStorable -e ' $a = XML::LibXML->load_xml(string => "<a></a>"); print Dumper $a; store($a, "tmp"); $b = retrieve "tmp"; print Dumper $b; ' $VAR1 = bless( do{\(my $o = 2150785512)}, 'XML::LibXML::Document' ); $VAR1 = bless( do{\(my $o = 2150785512)}, 'XML::LibXML::Document' ); PmmREFCNT_dec: REFCNT decremented below 0 for 803261e8! during global +destruction. Aborted (core dumped)

I get similar when I try using Dumper instead of Storable. I think it's because of XML::LibXML being XS object and Storable/Dumper only saves pointer to the memory without the actual data. On the other hand, I have no idea how to store / retrieve it correctly.

Dear Monks, do you have any good advice for me?

Replies are listed 'Best First'.
Re: Use Storable for storing XML::LibXML object
by tobyink (Abbot) on Jul 04, 2014 at 23:56 UTC

    The problem is that an XML::LibXML node is really just a pointer to a libxml struct that lives in XS land. It has no real meaning once the DOM is disposed of.

    What to do about it? Firstly, an important question. Say you've stored a node which represents a deeply nested XML element. Once you've retrieved the object from storage, should you only be allowed to query "down" from the node, or should $node->parentNode Just Work™?

      Thank you. Querying down from the node is enough in my case.

        Then you may be able to define a couple of hooks for freezing and thawing XML::LibXML::Element objects

        # these are completely untested! sub XML::LibXML::Elemment::STORABLE_freeze { my $self = shift; $self->toString; } sub XML::LibXML::Elemment::STORABLE_thaw { my $class = shift; my (undef, $str) = @_; XML::LibXML->parse_xml(string => $str)->documentElement; }

        See the "Hooks" section in the Storable documentation.

Re: Use Storable for storing XML::LibXML object
by McA (Priest) on Jul 04, 2014 at 15:00 UTC

    Hi buff,

    I'm not sure why you want to serialize the whole XML::LibXML thing. A XML file is a representation of structured data. So, would in not be enough to store the XML. As soon as you can load and parse the XML you have more or less the same state.

    I'm really interested in the use case of serializing the whole thing.

    Regards
    McA

      I came across this issue when I was trying to serialize objects which have XML::LibXML as member variables. I want to serialize the whole objects to have simple caching for case of repeated runs of the program.

Re: Use Storable for storing XML::LibXML object
by AppleFritter (Vicar) on Jul 04, 2014 at 17:59 UTC

      Thanks very much for the links!