Advertisement
musifter

AoC day 18 (pt2), Perl (dc transpiler)

Dec 18th, 2020
2,060
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 0.78 KB | None | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. print "0\n";
  7. while (<>) {
  8.     chomp;
  9.     my @stack;
  10.  
  11.     # assuming only one digit numbers
  12.     foreach my $tok (reverse split( / */ )) {
  13.         if ($tok =~ m#[0-9]#) {
  14.             print "$tok ";
  15.         } elsif ($tok eq '(') {
  16.             # parsing backwards, so ( is close, and ) is open
  17.             while ((my $pop = pop @stack) ne ')') {
  18.                 print $pop;
  19.             }
  20.         } else {
  21.             if ($tok eq '*') {
  22.                 # pop the higher order precidence +s from stack
  23.                 while (@stack && $stack[-1] eq '+') {
  24.                     print pop( @stack );
  25.                 }
  26.             }
  27.             push( @stack, $tok );
  28.         }
  29.     }
  30.     print reverse( @stack ), "+\n";
  31. }
  32. print "p\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement