<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">

use Parse::RecDescent;

#$RD_TRACE = 1;
#$RD_HINT = 1;

my $parser = Parse::RecDescent-&gt;new(&lt;&lt;'EOGRAMMAR');

    &lt;autoaction: { bless \%item, $item{__RULE__} } &gt;

	file:		element(s)

	element:	command | literal

	command:	'\\' literal options(?) args(?)

	options:	'[' option(s? /,/) ']'

	args:		'{' element(s?) '}'

	option:		/[^][\\$&amp;%#_{}~^ \t\n,]+/

	literal:	/[^][\\$&amp;%#_{}~^ \t\n]+/

EOGRAMMAR

local $/;
my $tree = $parser-&gt;file(&lt;DATA&gt;);

use Data::Dumper 'Dumper';
warn Dumper [ $tree ];

$tree-&gt;explain(0);

sub file::explain
{
	my ($self, $level) = @_;
	for (@{$self-&gt;{'element(s)'}})
	{
		$_-&gt;explain($level);
		print "\n";
	}
}

sub element::explain
{
	my ($self, $level) = @_;
	($self-&gt;{command}||$self-&gt;{literal})-&gt;explain($level)
}

sub command::explain
{
	my ($self, $level) = @_;
	print "\t"x$level, "Command: $self-&gt;{literal}{__PATTERN1__}\n";
	print "\t"x$level, "\tOptions:\n";
	$self-&gt;{'options(?)'}[0]-&gt;explain($level+2) if @{$self-&gt;{'options(?)'}};
	print "\t"x$level, "\tArgs:\n";
	$self-&gt;{'args(?)'}[0]-&gt;explain($level+2) if @{$self-&gt;{'args(?)'}};
}

sub options::explain
{
	my ($self, $level) = @_;
	$_-&gt;explain($level) foreach @{$self-&gt;{'option(s?)'}};
}

sub args::explain
{
	my ($self, $level) = @_;
	$_-&gt;explain($level) foreach @{$self-&gt;{'element(s?)'}};
}


sub option::explain
{
	my ($self, $level) = @_;
	print "\t"x$level, "Option: $self-&gt;{__PATTERN1__}\n";
}

sub literal::explain
{
	my ($self, $level) = @_;
	print "\t"x$level, "Literal: $self-&gt;{__PATTERN1__}\n";
}


__DATA__

\documentclass[a4paper,11pt]{article}
\usepackage{latexsym}
\author{D. Conway}
\title{Parsing \LaTeX{}}
\begin{document}
\maketitle
\tableofcontents
\section{Description}
...is easy \footnote{But not \emph{necessarily} simple}.
\end{document}
</pre></body></html>