# How to calculate a column of sums or test inequalities?

Given

``````34-2
34-5
34-3
``````

I'm looking to obtain

``````34-2=28
34-5=29
34-3=31
``````

Or, this would also be helpful: given:

``````34-2=5
34-5<=34
34-3=31
``````

I'm looking to obtain

``````!   34-2=5
34-5<=34
34-3=31
``````

Where! Is some indication that inequality or equality is false. I'm looking for something that processes text files.

-
In the second case, it would be real easy if the equality lines used double equals signs, such as "`34-2==5`" instead of just a single, since a single equals sign is used for assignment in most programming languages. – Daniel Andersson May 11 '12 at 15:17
I can change the signs to anything, so where it's =, I could put ==. – e a005 May 11 '12 at 15:18
Also, I assumed a *nix environment since you asked about that in a separate question very recently, but it would be good if you could clarify if you want a *nix solution specifically, or some other platform or the most general solution (Perl is quite general, but for other people answering it could be good to know). – Daniel Andersson May 11 '12 at 15:48

### First case

``````perl -nle 'print \$_."=".eval(\$_)' filewithexpressions
``````
• `-n` loops over the lines.
• `-l` strips newlines from `\$_`, but separates output lines with newlines for you.
• `-e` defines an expression to be run.
• `\$_` is a placeholder for "current line".
• `.` concatenates strings.
• `eval()` will take a string and evaluate it as code, so e.g. `eval('5+8')` returns `13`.

### Second case

With dual equals signs in the infile as noted in my comment to the original question:

``````perl -ne 'print eval(\$_)?" ":"!",\$_' filewithequalities
``````

As before in general.

• `-l` is not needed/wanted since the newlines take care of themselves in this case.
• The `?:` construct is a ternary operator. If the preceding expression is true, return a blank space, otherwise return an exclamation mark.
-
Good answer, complete and with an explanation. – e a005 May 11 '12 at 20:40

Here's a python script to handle the first part of your question:

``````import sys
for line in sys.stdin:
print "%s=%s" % (line.rstrip(), eval(line))
``````

Put the above code in `test.py`, put the input in `test.dat`, and run like so:

``````python test.py < test.txt
``````

I'm assuming a unix-like OS. Note that it can be dangerous to pass input to any script that runs `eval`---don't pass unknown data to this script.

-