Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- use strict;
- use warnings;
- my @Tok;
- #
- # Term := Number | ( Expression )
- #
- sub eval_term {
- my $ret;
- my $next = shift @Tok;
- if ($next =~ m#[0-9]#) {
- $ret = $next;
- } elsif ($next eq ')') {
- $ret = eval_expression( @Tok );
- $next = shift @Tok;
- if ($next ne '(') {
- die "Syntax error: Did not match paren: @Tok\n";
- }
- }
- return ($ret);
- }
- #
- # Expression := Term Operator Expression | Term
- # Operator := + | *
- #
- sub eval_expression {
- my $ret;
- return (0) if (!@Tok);
- $ret = &eval_term();
- if (@Tok) {
- my $peek = $Tok[0];
- if ($peek eq '+') {
- shift @Tok;
- $ret += eval_expression();
- } elsif ($peek eq '*') {
- shift @Tok;
- $ret *= eval_expression();
- }
- }
- return ($ret);
- }
- my $sum = 0;
- while (<>) {
- chomp;
- @Tok = reverse split( / */ );
- $sum += eval_expression();
- }
- print "Part 1: $sum\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement