No such thing as a small change | |
PerlMonks |
Re: Count Occurrences of a stringby Zaxo (Archbishop) |
on Sep 10, 2003 at 00:27 UTC ( [id://290248]=note: print w/replies, xml ) | Need Help?? |
Let's write this step by step. We will write a program called ctpA which takes a directory path as argument. The outpur file will be called pA.cat, written to the specified directory, and the program will overwrite any old pA.cat file. We want to run this as an interpreter script, so we start with a shebang line and shift in the directory argument. If there is none, we use the current working directory. The || operator brings in the default if no argument is given. To be careful, you should check $dir here for mischievous values. We need to look at all the files matching a naming pattern, so glob is the easy way to get a list of those names. Since we'll want the file names stripped out of the path for the summary we will write, we make the File::Basename module available. We also open the output file for writing.
We begin to look at the files one at a time by starting a for loop over their names. for (glob "${dir}/*.seq" ) { This makes $_ contain the file path for each in turn. We set the input record seperator, $/, to undef to slurp the entire file, open, read, and close, We get rid of all whitespace, including newlines, just in case there are some. $seq =~ s/\s//g; and do an anchored match at the tail of the string. This regex will match any $seq, since the putative tail may be of zero length. That regular expression makes A and N a character class and looks for the longest run of them at the end of the string. The parentheses capture the result to $1, used on the output line next. If there is no tail, the match still succeeds and length $1 is zero. That concludes the work to be done for a file, so we close the loop. All that remains is to close the output file. close OUT or die $!; This is untested - I don't have that sort of data around - but it is all straightforward stuff. After Compline,
In Section
Seekers of Perl Wisdom
|
|