Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Help with simple calculator script.

by Anonymous Monk
on Oct 24, 2003 at 15:39 UTC ( [id://301878]=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to make a script that if you type in - it does subtraction if i type in * it does multiplication so far I have

#!/usr/bin/perl print "What is your name?\n"; $name = <>; chomp($name); $greeting = "Hello, " . $name . "\nWhat do type of math do you want th +is program to do?\n"; print $greeting; print "What is the first number?\n"; $a = <>; chomp($a); print "What is the second number?\n"; $b = <>; chomp($b); print "Here is the answer\n"; $c = $a - $b; print $c; print "\nTada\n"; exit();

what need I add ?
Thank thee for thine wisdom

20031024 Edit by Corion: Added formatting
BazB: title changed as suggested.

Replies are listed 'Best First'.
Re: Help with simple calculator script.
by cchampion (Curate) on Oct 24, 2003 at 16:15 UTC

      The problem with Juerd's is that it offers no error checking. This one does:

      perl -ple'$_=eval||$@||0'

      For example:

      $ perl -ple'$_=eval' 1/0
      vs.
      $ perl -ple'$_=eval||$@||0' 1/0 Illegal division by zero at (eval 1) line 2, <> line 1.

      -sauoq
      "My two cents aren't worth a dime.";
      
Re: Help with simple calculator script.
by pg (Canon) on Oct 24, 2003 at 16:07 UTC
    This is Perl, make it simpler, and much more powerful:
    while (<STDIN>) { chomp; ($_ eq "quit") ? last : print eval "$_", "\n"; }
      This is what I have now what is wrong
      #!/usr/bin/perl print "What is your name?\n"; $name = <>; chomp($name); $greeting = "Hello, " . $name . "\nWhat do type of math do you want th +is program to do?\n"; print $greeting; chomp($operator = <STDIN>); if ($operator eq 'sub') { $c = $a - $b; } elsif ($operator eq '*') { # * code here } else { $c = 'invalid operator'; }

      Edit, BazB: closed code tag.

        This is what I have now what is wrong

        For one thing I've never known a calculator to need to know my name. That's kind of "2001: A Space Odyssey"-esque. Especially since I'm Dave. I can just see it now if I attempt to divide by zero: "I'm sorry Dave, I can't do that." It also reminds me of the fascenating little computer exhibits at the Exploratorium in San Fransisco that I used to love to play with back in 1978 when I was 10.

        Beyond that, the point that people are making with regards to using eval versus a logic tree, is that perl already knows how to do math. And Perl is an interpreted language, so dynamic code is perfectly alright. eval can be used to execute dynamic code. So by using eval, the Perl interpreter (perl) becomes the math engine for you. You don't have to go to all the trouble of teaching your Perl script how to add and subtract, and parse mathematical expressions, if perl already knows how to do that for you. The Perlish solution therefore, is to let perl parse the expression. (And this reminds me again of the common phrase, "Only perl can parse Perl." ...but in this case it can be rewritten as "Let perl parse it for you as dynamic Perl."

        eval does have its pitfalls. Because it would be perfectly happy to do whatever you ask of it as long as it is legal Perl. A mathematical expression is legal Perl. But so is something like " `rm -r /`". So you don't want to just give any old user access to a free eval from a CGI script or something. :)


        Dave


        "If I had my life to do over again, I'd be a plumber." -- Albert Einstein
Re: Help with simple calculator script.
by monktim (Friar) on Oct 24, 2003 at 16:14 UTC
    If it's a homework than maybe eval can't be used yet.

    You just need to read in the operator (- *) just like you read in the Name. Then you can use if.

    if ($operator eq '-') { $c = $a - $b; } elsif ($operator eq '*') { # * code here } else { $c = 'invalid operator'; }
    Read about the if statement and comparison operatiors (eq == ne !=).
Re: Help with simple calculator script.
by hardburn (Abbot) on Oct 24, 2003 at 16:32 UTC

    If those few operations are all you need, there's nothing wrong with the if/else dispatching above. However, if you ever want to extend it to other mathmatical operations, I'd use a dispatch table:

    my %OPERATIONS = ( '*' => sub { $_[0] * $_[1] }, '-' => sub { $_[0] - $_[1] }, '+' => sub { $_[0] + $_[1] }, ); # $operator, $first, and $second defined # elsewhere, from user input print "Result: ", $OPERATIONS{$operator}->($first, $second), "\n" if exists $OPERATIONS{$operator};

    Also, avoid using $a and $b as variable names, as they have special meaning in sort subroutines.

    ----
    I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
    -- Schemer

    :(){ :|:&};:

    Note: All code is untested, unless otherwise stated

Re: Help with simple calculator script.
by kutsu (Priest) on Oct 24, 2003 at 16:15 UTC

    add this:

    print $greeting; chomp($operator = <STDIN>); #your other prints and stuff here $c = $a - $b if $operator eq "-"; $c = $a * $b if $operator eq "*";

    The if statement could also be written as such:

    if ($operator eq "-") { $c = $a - $b; } else { $c = $a * $b; }

    "Pain is weakness leaving the body, I find myself in pain everyday" -me

Re: Help with simple calculator script.
by BUU (Prior) on Oct 24, 2003 at 16:10 UTC
    use strict; print "What operation?"; chomp(my $op=<>); if($op eq '-') { print $a-b; } elsif($op eq '*') { print $a*b; } #etc

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://301878]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (2)
As of 2024-04-20 03:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found