I realize the question name doesn’t really tell much but I didn’t really know how to explain it shortly, so here’s the long version.
First, here’s my current code:
#! /usr/bin/perl
use strict;
use warnings;
my $input;
while (<>) {
$input .= $_;
}
$input =~ s/ |\n//g;
print "\n";
What I want to do is make a calculator, e.g. when a user does echo "8 * 5 + 21-15" | calculate it will calculate it correctly. So here’s my thought progress. First I take the string as a whole and strip it of all whitespace characters. Then I wanted to index() it for the occurence of *, +, / or -. Then I wanted to add all the characters before any of those operators to a string and then (int) the string and then do the same to the part after the operator and then do the operation between them. But I don’t actually have much of a clue on how to do this. Also, I’m very new to Perl (3 days experience) so please go slowly on me if possible.
Thanks a lot.
If you can accept that your calculator won’t be able to handle parenthesis, use a regular expression to parse the string for you:
this will provide you with an array of tokens that you can work on, so
will print
Now it’s up to you to write some code that does the right calculations on the tokens. It isn’t too hard if you don’t try parsing parens, but if you do, you’ll need to write a recursive parser, which is much harder.