Please create an account to participate in the Slashdot moderation system

 



Forgot your password?
typodupeerror
×
User Journal

Journal darkewolf's Journal: Yes, I was bored... And I don't have a HP calculator. 1

#!perl
# lets write a RPN calculator for the fun of it
#
#
my @input;
my @operators;
my $scratch;
while($read = <STDIN>)
    {
        chomp($read);
        if($read =~ /EOI/)
            {
                exit 0;
            }
        if($read =~ /\+/)
            {
                $b = pop @input;
                $a = pop @input;
                $scratch = func_addition($a, $b);
                push @input, $scratch;
            }
        elsif($read =~ /\-/)
            {
                $b = pop @input;
                $a = pop @input;
                $scratch = func_subtraction($a, $b);
                push @input, $scratch;
            }
        elsif($read =~ /\//)
            {
                $b = pop @input;
                $a = pop @input;
                $scratch = func_division($a, $b);
                push @input, $scratch;
            }
        elsif($read =~ /\*/)
            {
                $b = pop @input;
                $a = pop @input;
                $scratch = func_multiply($a, $b);
                push @input, $scratch;
            }
        else
            {
            push @input, $read;
            }
        func_printstack(@input);
    }

exit 1;

sub func_printstack(@)
    {
        my @stack = @_;

        $size = $#stack + 1;
        print "[ ";
        for ($i = 0; $i < $size ; $i++)
            {
                print "$stack[$i] ";
            }
        print " ] \n";
    }

sub func_multiply($$)
{
    my($first, $second) =@_;
    my $answer;
    $answer = $first * $second;
    return $answer;
}
sub func_addition($$)
{
    my($first, $second) =@_;
    my $answer;
    $answer = $first + $second;
    return $answer;
}
sub func_subtraction($$)
{
    my($first, $second) =@_;
    my $answer;
    $answer = $first - $second;
    return $answer;
}
sub func_division($$)
{
    my($first, $second) =@_;
    my $answer;
    if($second != 0)
        {
        $answer = $first / $second;
        }
    else
        {
        print "Division by 0 fubar\n";
        exit 1;
        }
    return $answer;
}
This discussion has been archived. No new comments can be posted.

Yes, I was bored... And I don't have a HP calculator.

Comments Filter:
  • I know the code is very shocking. Infact, since it took me less than 3 minutes to write it I am not suprised. But I guess I wanted to make sure I understood RPN still. Guess I do.

Without life, Biology itself would be impossible.

Working...