1: #!/usr/bin/perl -w
   2: # i know everyone has written a calculator.
   3: # but im proud of this.
   4: # its the first useful thing ive written.
   5: # here we go
   6: 
   7: 
   8: use strict;
   9: 
  10: my $operation;
  11: my $int;
  12: my $int2;
  13: my $answer;
  14: my $runagain;
  15: 
  16: calculator();
  17: 
  18: sub calculator {
  19: 	print "What operation (Add, Sub, Mult, Divd) do you want to do? ";
  20: 	chomp($operation = <>);
  21: 	print "Enter the first number: ";chomp($int = <>);
  22: 	print "Enter the second number: ";chomp($int2 = <>);
  23: 	if ($operation =~ /^a/) {
  24: 		$answer = $int + $int2;
  25: 	} elsif ($operation =~ /^s/) {
  26: 		$answer = $int - $int2;
  27: 	} elsif ($operation =~ /^m/) {
  28: 		$answer = $int * $int2;
  29: 	} elsif ($operation =~ /^d/) {
  30: 		$answer = $int / $int2;
  31: 	}
  32: 	print "The answer is $answer\n";
  33: 	print "Do you want to run this again? ";chomp($runagain = <>);
  34: 	if ($runagain =~ /^y/) {
  35: 		calculator();
  36: 	} else {
  37: 		print "goodbye\n";
  38: 	}
  39: }

Replies are listed 'Best First'.
Re: Perl Calculator
by merlyn (Sage) on Mar 09, 2001 at 04:40 UTC
    Strangely enough, a 4-function calculator was the very first program I wrote (in BASIC) and executed (correctly the first time, I might add) some 30-ish years ago. Congratulations!

    -- Randal L. Schwartz, Perl hacker

Re: Perl Calculator
by damian1301 (Curate) on Mar 09, 2001 at 05:49 UTC
    Good job. You might want to add some more functions though. For example, the builtin sqrt(); function should be easy to implement. You could even check out greatest common factor by one of our fellow monks. With all that, you could carry this program on to be better than what it already is.Some other easy ideas would be to use powers (1 ** 2 1 to the second power) and simple modulus (4 %  3).

    Future: Use these math functions: tan, sin, cos, Lowest terms (for fractions), area, perimeter, and so on...

    Almost a Perl hacker.
    Dave AKA damian

    I encourage you to email me
Re: Perl Calculator
by Desdinova (Friar) on Mar 09, 2001 at 10:18 UTC
    Looking at this i got to thinking a calc program is a great way to learn perl.. You can start with something rather basic like above, and add more math functions as you learn then and even work up to using pattern matching so instead of a prompt for an operation it could take input like (4*5)/12 and stuff like that. The possiblities are almost endless I think i have a new ongoing hobby project..
Re: Perl Calculator
by -> (Initiate) on Mar 30, 2001 at 01:13 UTC
    Good job! :)

    You may want to add an i after your regexes, though...
    ie: /^s/i

    You're asking for Add, Sub, etc..(with caps in front) and checking in lowercase. (The i at the end says "case insensitive")