user2986250
user2986250

Reputation: 13

Arithmetic expression with eval in Perl

I have a problem about arithmetic expression in Perl.

I have already written the code but I couldn't fill inside of eval function.

Example:

>2+4

6

Another example:

>8-2*2

4

This is my program

#!/usr/bin/perl  

print ">";

while (<>) {   
  eval(---------);  
  print "\n>"; 
}

Upvotes: 0

Views: 839

Answers (3)

Oesor
Oesor

Reputation: 6652

You can chomp the input to remove the newline and use string eval.

#!/usr/bin/perl  
print ">" ;
while (<>) {
     chomp $_; 
     my $result = eval $_;  
     print "$result\n>"; 
}

Think about this: What happens when someone enters `rm *` at the prompt?

Upvotes: 2

Hatip Kabak
Hatip Kabak

Reputation: 326

You can just write in that way:

#!/usr/bin/perl 
print ">";

while (<>) {   
  print eval("$_");  
  print "\n>"; 
}

Upvotes: 0

Borodin
Borodin

Reputation: 126722

You aren't printing the result of eval. The calculation is being done, but you are just throwing it away and printing another prompt.

This should do as you want.

#!/usr/bin/perl  

print ">" ;

while (<>) {   
  print eval, "\n>";  
}

Upvotes: 0

Related Questions