#! /usr/bin/perl -w
use strict;
use HTML::Entities qw(encode_entities);
my @stack;
while (<>) {
while (/\G([^{}]+)|\G([{}])/g) {
if (length($1)) {
print encode_entities($1);
}
elsif ("{" eq $2) {
my $pos = pos($_);
if (/\G(\w+)/g) {
print "<$1>";
push @stack, $1;
}
else {
die "Unnamed opening brace at character $pos, line $.";
}
}
elsif (@stack) {
my $tag = pop(@stack);
print "$tag>";
}
else {
my $pos = pos($_);
die "Unmatched closing brace at character $pos, line $.";
}
}
}
if (@stack) {
die "Unclosed tags at end of file: '@stack'";
}