use strict; use warnings; use XML::Twig; my $twig = new XML::Twig (pretty_print => 'record'); my $root = new XML::Twig::Elt ('root'); $twig->set_root ($root); my @pendingSections; while () { chomp; if (/(.*)/i) { # deal with a header line # First pop any pending sections that need to be closed pop @pendingSections while @pendingSections > $1; while (@pendingSections < $1) { # Add section elements out to current header level my $level = @pendingSections + 1; my $elt = new XML::Twig::Elt ("section$level"); if ($level == 1) { $elt->paste (last_child => $root); } else { $elt->paste (last_child => $pendingSections[-1]); } push @pendingSections, $elt; } my $headElt = new XML::Twig::Elt ("head", $2); $headElt->paste (last_child => $pendingSections[-1]); } else { # It's a paragraph if (@pendingSections) { $pendingSections[-1]->suffix ("$_\n"); } else { $root->suffix ("$_\n"); } } } $twig->print (); __DATA__

Heading level 1

Heading level 2

Heading level 3

Heading level 2

Heading level 1 paragraph here paragraph here