Peter
Peter Campbell Smith

Stealthy calculations

Weekly challenge 143 — 13 December 2021

Week 143: 13 Dec 2021

Task 1

Task — 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.

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);
}

Output


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