Perl (Scripting) - Sum of integers in a file

by
Jeremy Canfield |
Updated: March 09 2020
| Perl (Scripting) articles
Let's say file1.txt contains integers.
5
-10
15.4
20
The following markup will get the sum of the integers in file1.txt. Running this will script will produce 30.4, which is the sum.
my $file = "/path/to/file.txt";
open(FH, "<", $file) or die "cannot open $file $! \n";
my $sum = 0;
while (my $line = <FH>) {
$sum += $line;
}
close FH;
print "$sum\n";
Did you find this article helpful?
If so, consider buying me a coffee over at