This is my first blog post regarding the Perl Weekly Challenge tirelessly maintained by Mohammad Anwar. Although I’ve been doing the challenge for a while now, I haven’t maintained my blog for years. Let’s change that!
This week’s challenge #2 from the Perl Weekly Challenge is a computer science classic: create a Reverse Polish Notation (RPN) calculator. This brings back fond memories.
Basic Algorithm
My Perl 5 and Raku solutions will both use the same basic algorithm. First, we tokenize the input into numbers and operators. Then, we loop through every token. For each token, we either:
- If the token is a number, we add it to the stack
- Otherwise, it’s an operator:
- Pull zero or more items off the stack depending on the operator
- Perform the required operation (e.g., addition, subtraction, etc.)
- Push the result onto the stack