use 5.16.3; use warnings; use autodie; open my $in, "<", "numbers.txt"; open my $out, ">", "sum.txt"; while (<$in>) { m{\S} or next; # skip empty lines m{^\s*#} and next; # skip comment lines m{^[-.0-9+*/ ]+$} or die "Line too dangerous to evaluate!"; # . for floats # pattern needs extending for math (sqrt, log, sin, cos, ...) support and exponentials with e notation # and 'x' for hexadecimal, '(', and ')' for grouping etc etc. Anyway, it is dangerous. # I'd not use eval for safety reasons, but if your validator is strict enough my $result = eval $_; $@ and die "Invalid expression on line $."; print $out $result; } close $in; close $out;