For playing with HTML, I prefer enforcing XHTML and playing with that, instead. Using XML::Twig. For example:

use strict; use warnings; use XML::Twig; my $html_code = ' <html> <head> <title>Glossary</title> </head><body> <!-- had to close head, open body --> <h1>Glossary</h1> <dl> <dt><b>E Definition</b></dt> <dd>E - data</dd> <p></p> <dt><b>B Definition</b></dt> <dd>B - data</dd> <p></p> <dt><b>A_definition</b></dt> <dd>A data.</dd> <p></p> <dt><b>C definition</b></dt> <dd>C - data</dd> <p></p> </dl> </body> </html> '; my $twig = XML::Twig->new(pretty_print => 'indented'); $twig->parse($html_code); for my $dl ($twig->root()->get_xpath('//dl')) { my @entries; for my $el ($dl->children()) { $el->cut(); if ($el->gi() eq 'dt') { push @entries, [ $el ]; } else { push @{$entries[-1]}, $el; } } @entries = sort { $a->[0]->text() cmp $b->[0]->text() } @entries; for my $entry (@entries) { $_->paste(last_child => $dl) for @$entry; } print $dl->sprint(),"\n"; }
Tested. The only caveat is if you start getting funky characters that aren't part of standard XML, e.g., "&copy;". Then it's a bit more work. Still doable, but more work.


In reply to Re: HTML::TreeBuilder: sort a Definition List (<dl>) by Tanktalus
in thread HTML::TreeBuilder: sort a Definition List (<dl>) by svenXY

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.