Peter’s blog ✴ Week 143 ✴ 13 December 2021

THE WEEKLY CHALLENGE
Stealthy calculations

The Perl Camel

Task 1

Calculator

You are given a string, $s, containing a mathematical expression. Write a script to print the result of the mathematical expression. To keep it simple, please only accept + - * ().

Examples


Example 1:
    Input: $s = "10 + 20 - 5"
    Output: 25

Example 2:
    Input: $s = "(10 + 20 - 5) * 2"
    Output: 50

Analysis

All you need is eval, as the Beatles didn't quite sing.

I am sorry that the 'Try it' feature is currently working very slowly or not at all owing to some issue with my web hosting provider.

Try it 

Try running the script with any input:



example: 1 + (2 * 3) / 4

Script


#!/usr/bin/perl

# Peter Campbell Smith - 2021-12-13
# PWC 143 task 1

use v5.20;
use warnings;
use strict;

my ($test, @tests);

# inputs
@tests = ("10 + 20 - 5", "(10 + 20 - 5) * 2", "(12345 * 6789) / 23 + 1 / 77");

# eval will do it
for $test (@tests) {
    say qq[\nInput:  \$s = $test\nOutput: ] . eval($test);
}

7 lines of code

Output from script


Input:  $s = 10 + 20 - 5
Output: 25

Input:  $s = (10 + 20 - 5) * 2
Output: 50

Input:  $s = (12345 * 6789) / 23 + 1 / 77
Output: 3643921.96950875

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain