Advertisement
musifter

AoC day 18, Perl (Recursive Descent)

Dec 18th, 2020 (edited)
1,688
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.02 KB | None | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. my @Tok;
  7.  
  8. #
  9. # Term := Number | ( Expression )
  10. #
  11. sub eval_term {
  12.     my $ret;
  13.  
  14.     my $next = shift @Tok;
  15.     if ($next =~ m#[0-9]#) {
  16.         $ret = $next;
  17.     } elsif ($next eq ')') {
  18.         $ret = eval_expression( @Tok );
  19.         $next = shift @Tok;
  20.         if ($next ne '(') {
  21.             die "Syntax error: Did not match paren: @Tok\n";
  22.         }
  23.     }
  24.  
  25.     return ($ret);
  26. }
  27.  
  28. #
  29. # Expression := Term Operator Expression | Term
  30. # Operator := + | *
  31. #
  32. sub eval_expression {
  33.     my $ret;
  34.  
  35.     return (0)  if (!@Tok);
  36.  
  37.     $ret = &eval_term();
  38.  
  39.     if (@Tok) {
  40.         my $peek = $Tok[0];
  41.         if ($peek eq '+') {
  42.             shift @Tok;
  43.             $ret += eval_expression();
  44.         } elsif ($peek eq '*') {
  45.             shift @Tok;
  46.             $ret *= eval_expression();
  47.         }
  48.     }
  49.  
  50.     return ($ret);
  51. }
  52.  
  53. my $sum = 0;
  54. while (<>) {
  55.     chomp;
  56.     @Tok = reverse split( / */ );
  57.     $sum += eval_expression();
  58. }
  59.  
  60. print "Part 1: $sum\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement