获取perl字符串计算结果 [英] Get the perl string calculation result
本文介绍了获取perl字符串计算结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果一个字符串如下表示$str = "5+2-1";我想从该字符串中获取计算结果.我如何转换为标量来计算这个?谢谢.
If one string is expressed like below $str = "5+2-1"; I'd like to get the calculation result from that string. How do I convert to scalar to compute this? Thanks.
推荐答案
最简单的方法:
print eval('5+2-1');
但它不安全:
print eval('print "You are hacked"');
您需要在 eval
之前检查字符串.您也可以使用 Math::Expression 模块或来自 cpan 的许多其他模块:
You need to check string before eval
it.
Also you can use Math::Expression module or many other modules from cpan:
#!/usr/bin/perl
use strict;
use warnings;
use Math::Expression;
my $env = Math::Expression->new;
my $res = $env->Parse( '5+2-1' );
# my $res = $env->Parse( 'print you are hacked' ); # no math expression here
print $env->Eval( $res );
这篇关于获取perl字符串计算结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文