Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Count Occurrences of a string

by Zaxo (Archbishop)
on Sep 10, 2003 at 00:27 UTC ( [id://290248]=note: print w/replies, xml ) Need Help??


in reply to Count Occurrences of a string

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.

#!/usr/bin/perl -w use strict; die 'Usage: ctpA [DIR]' if @ARGV > 1; my $dir = shift || '.';
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.
use File::Basename; open local(*OUT), "> $dir/pA.cat" or die $!;

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,

local $/; open local(*IN), "< $_" or die $!; my $seq = <IN>; close IN or die $!;
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.
$seq =~ /([AN]*)$/; printf OUT "%d %s.seq\n", length $1, basename $_; }
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,
Zaxo

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://290248]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (4)
As of 2024-04-20 12:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found