#!/usr/bin/perl # Example parser. # Parses thingies. # eg: # thingy { # foo # bar # baz # thingy { # some # sub # thingy # filler # thingy { # and some more crap # } # } # } use strict; sub peek_tok { my ($toks) = @_; return $toks->[0] } sub next_tok { my ($toks) = @_; return shift @$toks; } sub parse_thingy { my ($toks) = @_; my $tok; print "Entering thingy\n"; # don't swallow "thingy" unless we're actually parsing # a thingy block if (peek_tok($toks) ne "thingy") { $tok = peek_tok($toks); print "got ''\n"; return "failure"; } # ditch "thingy" token next_tok($toks); if (next_tok($toks) ne "{") { die "Expected '{' in thingy block"; } while (($tok = peek_tok($toks)) =~ /[a-zA-Z0-9]+/) { if ($tok eq "thingy") { parse_thingy($toks); } else { print "this thingy has $tok\n"; next_tok($toks); } } if ($tok ne '}') { die "Unrecognized token $tok in thingy, expected '}'"; } print "Exiting thingy"; return "success"; } # vars for a file my $term = $/; my $tokens; my $fc; my @split_input; # slurp in a file undef $/; $fc = <>; $/ = $term; # split into tokens and take an array reference to the returned value @split_input = split(/[\t \n]+|([\'\(\)])|(".*?")/, $fc); # delete empty fields that split sometimes puts in. for (@split_input) { if (/^$/) { next; } push(@$tokens, $_); } print parse_thingy($tokens), "\n";