use strict; use warnings; my @files = grep /^output\d+$/, ; foreach my $file ( @files ) { open (IN, "<$file") or die "could not open $file: $!"; print "$file\n"; my ($total,$i) = (0,0); #initialize to zero for each file while ( my $input = ){ #sine you don't seem to be using $x, $y, $z anyhow my $sum = (split /\s+/,$input)[3]; $total += $sum; $i++; my $div = $total/$i; my $sqrt = sqrt($div); print "$total\n"; open (OUT2, ">RMSD$file") or die "could not open RMSD$file: $!"; print OUT2 "$sqrt\n" } }