All pastes #708749 Raw Edit

Anonymous

public text v1 · immutable
#708749 ·published 2007-09-24 03:04 UTC
rendered paste body
#!/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 $tok;
    my ($toks) = @_;
    $tok = shift @$toks;
    return $tok;
}

sub parse_thingy_items
{
    my ($toks) = @_;
    my $tok;

    if (($tok = peek_tok($toks)) eq "thingy") {
        parse_thingy($toks);
        parse_thingy_items($toks);
    } elsif ($tok =~ /[a-zA-Z0-9]/) {
        print "this thingy has $tok\n";
        next_tok($toks);
        parse_thingy_items($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 (($tok = next_tok($toks)) ne "{") {
        die "Expected '{' in thingy block, but got '$tok'";
    }
    parse_thingy_items($toks);
    if (($tok = next_tok($toks)) ne '}') {
        die "Unrecognized token $tok in thingy, expected '}'";
    }
    print "Exiting thingy\n";
    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";