FreeKB - Sum of integers in a file in Perl
Sum of integers in a file in Perl

Home > Search

Let's say file1.txt contains integers.



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";


Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

Please enter in the box below so that we can be sure you are a human.