将strnig用作Perl中计算器程序的输入 [英] Taking strnig as input for calculator program in Perl

查看:34
本文介绍了将strnig用作Perl中计算器程序的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Perl的新手,我正在尝试创建一个简单的计算器程序,但是规则与常规数学有所不同.所有运算具有相同的功效,必须从左到右解决数学问题.这是一个示例:

I am new to Perl and I'm trying to create a simple calculator program, but the rules are different from normal maths. All operations have the same power and the math problem must be solved from left to right. Here is an example:

123-10 + 4 * 10 =((123-10)+ 4)* 10 = 1170

123 - 10 + 4 * 10 = ((123 - 10) + 4) * 10 = 1170

8 * 7/3 + 2 =((8 * 7)/3)+ 2 = 20.666

8 * 7 / 3 + 2 = ((8 * 7) / 3) + 2 = 20.666

因此,在第一种情况下,用户需要输入一个字符串:123-10 + 4 * 10.我该如何完成这项任务?很抱歉,这不是一个普遍的问题,但是我不确定该如何开始.我需要柜台吗?就像-字符串的第二个字符是一个运算符,而侧面的两个都是数字.

So in the first case the user needs to enter one string: 123 - 10 + 4 * 10. How do i approach this task? I'm sorry if it's too much of a general question, but i'm not sure how to even begin. Do i need a counter? Like - every second character of the string is an operator, while the two on the sides are digits.

推荐答案

恐怕我很懒,所以我解析时将使用正则表达式和进程进行解析.

I'm afraid I'm lazy so I'll parse with a regex and process as I parse.

#!/usr/bin/env perl

#use Data::Dumper;
use Params::Validate (':all');
use 5.01800;
use warnings;

my $string=q{123 - 10 + 4 * 10};

my $result;
    sub fee {
        my ($a)=validate_pos(@_,{ type=>SCALAR });
        #warn Data::Dumper->Dump([\$a],[qw(*a)]),' ';
        $result=$a;
        };
    sub fi {
        my ($op,$b)=validate_pos(@_,{ type=>SCALAR},{ type=>SCALAR });
        #warn Data::Dumper->Dump([\$op,\$b],[qw(*op *b)]),' ';
        $result = $op eq '+' ? $result+$b :
                  $op eq '-' ? $result-$b :
                  $op eq '*' ? $result*$b :
                  $op eq '/' ? $result/$b :
                  undef;
        #warn Data::Dumper->Dump([\$result],[qw(*result)]),' ';
        };

$string=~ m{^(\d+)(?{ fee($1) })(?:(?: *([-+/*]) *)(\d+)(?{ fi($2,$3) }))*$};
say $result;

请注意使用(?{...})1

Note the use of (?{...}) 1

这篇关于将strnig用作Perl中计算器程序的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆