Sum of integers in a file in Perl

Home > Search
  by

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 (<FH>) {
  $sum += $_;
}

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.




Comments