Want to read Slashdot from your mobile device? Point it at m.slashdot.org and keep reading!

 



Forgot your password?
typodupeerror
×
User Journal

Journal 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;
}
User Journal

Journal Journal: Oh well

I seem to have journals everywhere. Why not one place more. I prefer my one at LJ but hey. To each their own.

Slashdot Top Deals

New York... when civilization falls apart, remember, we were way ahead of you. - David Letterman

Working...