Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the perl string calculation result

Tags:

string

perl

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.

like image 440
Cumulus Avatar asked Nov 30 '22 00:11

Cumulus


2 Answers

The easiest way to do this:

print eval('5+2-1');

but it's not safe:

print eval('print "You are hacked"');

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 );
like image 148
Suic Avatar answered Dec 20 '22 10:12

Suic


If you are sure the string does not contain any malicious code you can use eval to treat the content of it as perl code.

#!/usr/bin/perl
use strict;
use warnings;

my $string = "5+2-1";

print eval($string);
#print 6    
like image 33
edi_allen Avatar answered Dec 20 '22 10:12

edi_allen