#!/usr/bin/perl -W
use strict;
use HTML::TreeBuilder;
my $tree = HTML::TreeBuilder->new_from_content(<<'END') or die;
Glossary
Glossary
- E Definition
- E - data
- B Definition
- B - data
- A_definition
- A data.
- C definition
- C - data
END
my $dl = $tree->look_down( _tag => 'dl' );
# Unlink all of $dl's children from $dl, and return them.
my @dl_content = $dl->detach_content();
# Group the tags into an AoA on the DT tag.
my @dt_tag_clusters;
foreach (@dl_content) {
push @dt_tag_clusters, [] if $_->tag() eq 'dt';
die "Tags occured before first DT" unless @dt_tag_clusters;
push @{ $dt_tag_clusters[-1] }, $_;
}
# Sort the clusters
@dt_tag_clusters = map { $_->[1] }
sort { $a->[0] cmp $b->[0] }
map { [ $_->[0]->as_HTML, $_ ] }
@dt_tag_clusters;
# Un-cluster the tags.
@dl_content = map { @$_ } @dt_tag_clusters;
# Replace the DL's content with the sorted tags.
$dl->push_content( @dl_content );
print $tree->as_HTML; # or use HTML::PrettyPrinter
$tree = $tree->delete();