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


SUBMITTED BY: PCSlim

DATE: Dec. 19, 2020, 3:53 a.m.

FORMAT: Perl

SIZE: 798 Bytes

HITS: 376

  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. print "0\n";
  5. while (<>) {
  6. chomp;
  7. my @stack;
  8. # assuming only one digit numbers
  9. foreach my $tok (reverse split( / */ )) {
  10. if ($tok =~ m#[0-9]#) {
  11. print "$tok ";
  12. } elsif ($tok eq '(') {
  13. # parsing backwards, so ( is close, and ) is open
  14. while ((my $pop = pop @stack) ne ')') {
  15. print $pop;
  16. }
  17. } else {
  18. if ($tok eq '*') {
  19. # pop the higher order precidence +s from stack
  20. while (@stack && $stack[-1] eq '+') {
  21. print pop( @stack );
  22. }
  23. }
  24. push( @stack, $tok );
  25. }
  26. }
  27. print reverse( @stack ), "+\n";
  28. }
  29. print "p\n";

comments powered by Disqus