in reply to files stored in an array

I don't see why files would be included twice. Why don't you start out by printing the content of @files to see if it contains duplicates?

Also, your script won't compile under strictures. And it uses bare filehandles instead of lexically scoped ones. And it does that without ever closing any files after use. It also never checks to be sure that a file got properly opened.

I've taken a minute or two to alter your code just enough to get it to pass strictures, and to explicitly close filehandles. I've also used lexical filehandles, which actually would close themselves when they fall out of scope, so my 'close' lines are somewhat redundant. I've also added the classical "or die..." mechanism to your file opens, so that if a file is failing to open you'll know about it.

Here's the code...

use strict; use warnings; my @files = grep /^output\d+$/, <output*>; my ( $total, $i ); foreach my $file (@files) { open ( my $in, "<$file" ) or die "Couldn't open $file: $!\n"; while ( my $input = <$in>) { print "$file\n"; my ($x, $y, $z, $sum) = split (/\s+/, $input); $total += $sum; $i++; my $div = $total/$i; my $sqrt = sqrt($div); print "$total\n"; open ( my $out2, ">RMSD$file") or die "Couldn't open RMSD$file: $!\n"; print $out2 $sqrt; close $out2; } close $in; }

Update: I missed the mark on the actual problem, and others were correct in finding that you're printing to the output file once per line. You're also opening the output file once per line... it hasn't been mentioned, but each time you open the file for output in the way you are, it clobbers whatever the file contained previously. That's kinda a mess. ...my example didn't fix that either, but it's certanly worth mentioning.


Dave

Replies are listed 'Best First'.
Re^2: files stored in an array
by ysth (Canon) on Aug 08, 2004 at 22:08 UTC
    And it uses bare filehandles instead of lexically scoped ones. And it does that without ever closing any files after use.
    There are worse things in the world than that. And as a matter of fact it does close every file but the last one. Lexically scoped filehandles are neat, and should definitely be used in a subroutine or a module, but I don't see pressing need to convert newbies to their use in the main code of a script. I also am not sure I see the point of doing an explicit close unless you want to take some action if it returns an error.