http://www.perlmonks.org?node_id=890482


in reply to incrementing already existing file

wanttoprogram:

If you keep your indentation and other whitespace consistent and clean, it's easier to see errors in your code. Additionally, I like to declare variables where I need them, and I don't create variables I don't use. ;^) (In other words, I deleted a few variables that you weren't using.) So I altered your code a bit, like this:

#!/usr/bin/perl -w use strict; open (MYFILE, "2hgs_d00_internal_nrg_e.dat"); open (NEWF, "2HGS_bio_conv-min_p.pdb"); while (<MYFILE>) { chomp; # avoid \n at the end of each line if ($_ =~/ENERGY/) { for(my $count=1;$count<=1;$count++){ my $chn = substr $_, 20, 3; my $nrgval = substr $_, 35, 8; while (<NEWF>) { chomp; # avoid \n at the end of each line if ($_ =~/ATOM/){ for(my $count2=1;$count2<=1;$count2++){ my $chn2 = substr $_, 23, 3; my $toprint = substr $_, 0, 65; for($chn=1;$chn<=$chn2;$chn++){ if ($chn==$chn2){ print " $toprint $nrgval \n"; } } } } } } } }

Having done that, it's a bit easier to see why you get only one value from MYFILE. You read from it in the outermost loop, and then process the entire NEWF file. Then, when it's time to read the second record from MYFILE, your NEWF is empty, so it completely skips the inner loop from then on.

Generally, if your code just creeps rightward like this, it's indicative of a problem of some sort. I'm normally uncomfortable with more than, say, four levels of indentation. Beyond that, I tend to either change my logic, or pull out some subroutines to simplify things.

One last thing: You have some strange loops in the form:

for(count2=1;$count2<=1;$count2++){ #stuff }

You know that the loop should execute only one time, right? I would normally assume you meant something else and just keyed in the wrong thing. But since you have it repeated I thought I'd point it out to you. For example, try this program out:

#!/usr/bin/perl for (my $count2=1; $count2<=1; $count2++) { print "Count2: $count2\n"; }

You should review how loops work, and then change the logic to do more of what you want. If you're wanting to work through both files in parallel, you might want to check out the logic in Re: How to deal with Huge data and/or Re: parallel reading.

...roboticus

When your only tool is a hammer, all problems look like your thumb.