Raghav2580
Raghav2580

Reputation: 248

how to read arithmetic data from text file and handle operations in perl

I have a text(example.txt) file which has numbers and arithmetic operations e.g.
10+5*6
8+(4*3)
...
I want to handle these operations and generate output like below in another text file (output.txt)
10 + 5 * 6 = 40
8 + (4 * 3) = 20
...
I'm new to perl, so your help would be appreciated.

Upvotes: 0

Views: 140

Answers (2)

mpapec
mpapec

Reputation: 50637

perl -MSafe -lnE 'say "$_ = ", Safe->new()->reval($_) //"failed"' example.txt

perldoc Safe - Compile and execute code in restricted compartments

Upvotes: 3

Vorsprung
Vorsprung

Reputation: 34297

This ignores any security concerns

perl -ln -e '$a=eval; print "$_ = $a";' < examples.txt 

Upvotes: 0

Related Questions