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

Hi, I'm new to Perl and need to output some XML documents. So I found a module and can create a document, like this:
use strict; use XML::Generator; open (RPT, ">menu.xml"); my $gen = XML::Generator->new( 'escape' => 'always', 'pretty' => 2); my $xml = $gen->Menu( $gen->Course("Appetizers"), $gen->Items( $gen->Name("Soup"), $gen->Name("Salad") ), $gen->Course("Entres"), $gen->Items( $gen->Name("Oysters"), $gen->Name("Pizza") ) ); print RPT "$xml";
But the document needs to be dynamic, so I tried foreach loops like this:
use strict; use XML::Generator; open (NEWRPT, ">newmenu.xml"); my %myhash = ( "Appetizers" => ["Soup", "Salad"], "Entres" => ["Oysters", "Pizza"] ); my $newgen = XML::Generator->new( 'escape' => 'always', 'pretty' => 2); my $newxml = $newgen->Menu( foreach my $course (keys %myhash) { $newgen->Course("$course"), $newgen->Items( my @items = @{$myhash{$course}}; foreach my $item (@items) { $newgen->Name("$item") }) }); print NEWRPT "$newxml";
But this fails at the 1st foreach. I've searhed several places, but have not yet found a solution. Is a loop like this possible? Am I taking the wrong approach? Thank you, Martin

Replies are listed 'Best First'.
Re: XML::Generator loop
by theguvnor (Chaplain) on Nov 06, 2001 at 05:29 UTC

    Hi Martin.

    I will not offer an iron-clad guarantee, but I believe that your second try (with the loops) is failing because you are passing the Menu method a code block - in this case, your foreach loop.

    I would try reversing it: put the call to $newgen->Menu inside the foreach loop. Of course that means that you'd have to build up $newxml piece by piece using the .= operator rather than all at once.

    Like I said, this is just my reaction to it without actually testing...... since you indicated you're new to Perl, I'll offer the following advice that I wish I'd known when I started: if you run your program from the command prompt with the -c option, it compiles it without running it, and seems to give much more informative error messages.

    Hope it helps....

      Guv, Thank you for the suggestion. I hadn't thought about turning my program inside-out. The '-c' switch is new to me too, thanks! Martin
Re: XML::Generator loop
by impossiblerobot (Deacon) on Nov 06, 2001 at 04:32 UTC
    I don't have a lot of experience with XML, but I've been using XML::Simple, which really is simple to use.

    It allows you to build your data structure using Perl hashes, then output it as XML.
    (You can also read the XML file back in the same way.)

    Impossible Robot
      IR, Thank you for the tip, I'll take a look at it. Martin