Stealthy calculations
Weekly challenge 143 — 13 December 2021
Week 143: 13 Dec 2021
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 + - * ().
Example 1: Input: $s = "10 + 20 - 5" Output: 25 Example 2: Input: $s = "(10 + 20 - 5) * 2" Output: 50
All you need is eval
, as the Beatles didn't quite sing.
#!/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); }
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