A while back I wrote a script to take care of an events schedule on a web site. It reads data from an XML file (such as title, date, description, URL, etc.) puts the data in a hash and rearranges it into HTML for output. Of course, it also watches the current date, and makes sure past events don't show up, and other tricks like that. It has been a real time-saver.

Lately I've been finding other potential uses for the script on the site. The problem is, I've got code in the script which is very specific for that particular XML file. For instance, the routines that turn the data into HTML - they expect very specific input:

sub basic_list { my (%entry) = @_; if ($entry{'subtitle'} ne "") { $entry{'subtitle'} = "<h4>$entry{'subtitle'}</h4>" } print <<END; <li><h3>$entry{'title'}</h3>$entry{'subtitle'}$entry{'long_date'}<br/> +$entry{'description'}</li> END }
Right now, if I want to handle a different XML file with different elements, I have to make a copy of my script and retrofit it.

But I don't want to go making a dozen scripts which are 99% the same and 1% different. (I also don't want to muck about in my lovingly crafted script every time I want to change the way my HTML output looks.) I know there's got to be a better way to do this, to separate out the details and make one program that works with all the XML files I throw at it. It's probably something really simple that I just haven't learned yet.

What's my best strategy here? I toyed with the idea of putting specific subroutines like the one above in the XML file itself, letting my script read and execute them, but I'm not sure if that's really the way to go. Is that ever done?


In reply to one script, not twelve nearly identical ones! by drewbert

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.