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.
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 );
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With