Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Summing numbers in a file

by Tux (Canon)
on Jun 03, 2020 at 10:40 UTC ( [id://11117639]=note: print w/replies, xml ) Need Help??


in reply to Summing numbers in a file

I wonder why most of this thread is talking about file handle safety and none of those even mention what will happen if a line in the file is rm -rf /. (thanks for the posts that did mention "do not use eval". eval is dangerous!)

I would not even consider testing this script without a minimal validation of it's input. A start could be:

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!"; # . fo +r floats # pattern needs extending for math (sqrt, log, sin, cos, ...) supp +ort and exponentials with e notation # and 'x' for hexadecimal, '(', and ')' for grouping etc etc. Anyw +ay, it is dangerous. # I'd not use eval for safety reasons, but if your validator is st +rict enough my $result = eval $_; $@ and die "Invalid expression on line $."; print $out $result; } close $in; close $out;

Enjoy, Have FUN! H.Merijn

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11117639]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2024-03-28 08:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found