While there are some cosmetic issues I'd like to raise, the heart of your issue with the posted code is that you have not wrapped your output-to-file call to pos in the same while loop that you wrapped your output-to-screen block. Except, of course, then you try to output them both simultaneously, which is problematic because the first time through, you used two different loops. The following does what (I think) you intend:
with minimal changes to code. Note that this opens a file with a white space in the name, which is likely not what you intended and makes dealing with files generally a bigger pain.#!/usr/bin/perl -w $str="BATCATDATEFEAT"; $A=0;$T=0; while ($str=~ /A/ig) {$A++;# Line 4 print"\n A=$A ends at ",pos $str,"\n";} while ($str=~ /T/ig) {$T++; print"\n T=$T ends at ",pos $str,"\n";} $output="Results .txt"; # Line 8 unless (open(RESULT,">$output")){ print"Cannot open file\"$output\".\n\n"; exit; # Line 11 } # Line 12 $A=0;$T=0; while ($str=~ /A/ig) {$A++;# Line 4 print RESULT "\n A=$A ends at ",pos $str,"\n";} while ($str=~ /T/ig) {$T++; print RESULT "\n T=$T ends at ",pos $str,"\n";} close(RESULT); # Line 17 exit;
You may want to check out open and die for some more readable code, strict for making debugging easier, and you may want to add line breaks and indents to make flow more obvious. So a cleaner version of this code may look like:
#!/usr/bin/perl -w use strict; my $str="BATCATDATEFEAT"; my $A=0; my $T=0; while ($str =~ /A/ig) { $A++;# Line 4 print "\n A=$A ends at ",pos $str,"\n"; } while ($str =~ /T/ig) { $T++; print"\n T=$T ends at ",pos $str,"\n"; } my $output="Results.txt"; # Line 8 open(my $fh, ">", $output) or die "Cannot open file '$output'.\n\n"; $A=0; $T=0; while ($str=~ /A/ig) { $A++; print $fh "\n A=$A ends at ",pos $str,"\n"; } while ($str=~ /T/ig) { $T++; print $fh "\n T=$T ends at ",pos $str,"\n"; }
#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.
In reply to Re: How can I get the results in a text file from counting in a string?
by kennethk
in thread How can I get the results in a text file from counting in a string?
by supriyoch_2008
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |