Bootstrap FreeKB - Perl (Scripting) - Sum of integers in a file
Perl (Scripting) - Sum of integers in a file

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


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