I am new to Perl and attempting to parse XML into an array of hashes using XML::Parser.
The script parses each child element of a <story> element into a hash. A reference to the hash is pushed on an array. When printing out the array of hashes, only the values from the last element parsed are displayed.
Overwriting the global hash is probably causing the problem.
I would like to either:
Create a lexically scoped hash variable but I am having difficulty due to the event driven XML::Parser subs (StartTag, EndTag, and Text)
Effectively deal with the global hash variable (by redefining it?)
thanks in advance monks -
use strict; use XML::Parser; use LWP::Simple; my @curr; my @stories; # global hash my %story; my $xml = get("http://www.slashdot.org/slashdot.xml"); die "Failed to obtain xml " unless defined($xml); my $p = XML::Parser->new(Style => 'Stream'); $p->parse($xml); # print out the results foreach my $hashref (@stories) { print "$hashref->{title}\n"; } # StartTag - called when the start of an XML tag is found sub StartTag { my($p, $tag) = @_; push @curr, $tag; } # EndTag - called when the end of a XML tag is seen sub EndTag { my($p, $tag) = @_; # pushes the hash ref onto the array if ($tag eq 'story') { push @stories, \%story; } pop @curr; } # Text - called when text data is encountered sub Text { unless ($curr[-1] eq 'story') { $story{$curr[-1]} = $_; } }
Example of a story element
<story> <title>Debian And WineX</title> <url>http://slashdot.org/article.pl?sid=02/05/28/1515220</url> <time>2002-05-28 18:25:01</time> <author>Hemos</author> ... </story>

In reply to Problem with a Ref to a global variable while using XML::Parser by beamsack

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.