Let's say I have the following html that is an outline using header tags:

<h1>blah</h1> <p>blah<p> <h2>blah</h2> <p>blah</p> <h3>blah</h3> <p>blah</p> <h2>blah blah blah</h2> <p>blah</p> <h1>blah</h2> <h2>blah</h2> <h2>blah</h2>

I want to convert that to this, wrapping each h2 with a div:

<h1>blah</h1> <p>blah<p> <div> <h2>blah</h2> </div> <div> <p>blah</p> <h3>blah</h3> <p>blah</p> </div> <div> <h2>blah blah blah</h2> <p>blah</p> </div> <h1>blah</h1> <div> <h2>blah</h2> </div> <div> <h2>blah</h2> </div>
In other words, the algorithm must search for all h2 tags, then find the next sibling tag that is not an h1 tag or EOF, and wrap that section in a div tag. HTML::Element and HTML::TreeBuilder seem like the right tools for the job but this problem seems so common I'm wondering if there is something that works out of the box for dealing with HTML that is set up like an outline.

$PM = "Perl Monk's";
$MCF = "Most Clueless Friar Abbot Bishop Pontiff Deacon Curate Priest Vicar";
$nysus = $PM . ' ' . $MCF;
Click here if you love Perl Monks


In reply to Wrapping HTML "sections" with a div by nysus

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.