diff options
| author | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2023-04-26 22:17:05 +0200 |
|---|---|---|
| committer | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2023-04-29 21:05:07 +0200 |
| commit | e4c2dc90eba3b5454876b9613fb6717a26632934 (patch) | |
| tree | 7df83079df8c8d60e3cc4b5d788d8d0180759581 | |
| parent | 579fa7b88b8b452e6c7b52cb203c72cefab01a1c (diff) | |
| download | perlweeklychallenge-club-e4c2dc90eba3b5454876b9613fb6717a26632934.tar.gz perlweeklychallenge-club-e4c2dc90eba3b5454876b9613fb6717a26632934.tar.bz2 perlweeklychallenge-club-e4c2dc90eba3b5454876b9613fb6717a26632934.zip | |
Challenge 143 task 1
| -rwxr-xr-x | challenge-143/jo-37/perl/ch-1.pl | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/challenge-143/jo-37/perl/ch-1.pl b/challenge-143/jo-37/perl/ch-1.pl new file mode 100755 index 0000000000..3dcec9d792 --- /dev/null +++ b/challenge-143/jo-37/perl/ch-1.pl @@ -0,0 +1,57 @@ +#!/usr/bin/perl -Ts + +use v5.24; +use Test2::V0; +use experimental 'signatures'; + +our ($tests, $examples); + +run_tests() if $tests || $examples; # does not return + +die <<EOS unless @ARGV; +usage: $0 [-examples] [-tests] [--] [EXPR] + +-examples + run the examples from the challenge + +-tests + run some tests + +EXPR + arithmetic expression made of digits, whitespace, '+', '-', '*' and + parentheses + +EOS + + +### Input and Output + +say calculator(shift); + + +### Implementation + +sub calculator ($s) { + # Laundering the input string: + $s =~ /^([-+*\d\s()]*)$/ or return "expression invalid: $s"; + my $result = eval $1; + $@ ? $@ : $result; +} + + +### Examples and tests + +sub run_tests { + SKIP: { + skip "examples" unless $examples; + is calculator('10 + 20 - 5'), 25, 'example 1'; + is calculator('(10 + 20 - 5) * 2'), 50, 'example 2'; + } + + SKIP: { + skip "tests" unless $tests; + } + + done_testing; + exit; +} |
