Get the perl string calculation result

后端 未结 2 1619
终归单人心
终归单人心 2021-01-19 18:04

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.

相关标签:
2条回答
  • 2021-01-19 18:43

    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 );
    
    0 讨论(0)
  • 2021-01-19 18:53

    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    
    
    0 讨论(0)
提交回复
热议问题