Skip to content

Instantly share code, notes, and snippets.

@aurorapar
Created April 28, 2017 11:22
Show Gist options
  • Save aurorapar/8bfcc49d7bea6bf0895fc777df1319f7 to your computer and use it in GitHub Desktop.
Save aurorapar/8bfcc49d7bea6bf0895fc777df1319f7 to your computer and use it in GitHub Desktop.
Pattern matching one read file in another read file
#not /usr/local/bin/perl
# Reports a match and position of a Motif
#
# Input:
# One motif pattern file
# One sequence file
$patternFile;
$searchFile;
displayPrompt();
printf "\nMotif pattern file: " . $patternFile . "\n" . "Sequence file: " . $patternFile . "\n";
$patternText = readFile($patternFile);
$searchText = readFile($searchFile);
print "\n\nMotif pattern text:\n" . $patternText . "\n\nSequence text:\n" . $searchText . "\n\n";
if($searchText =~ /$patternText/)
{
print "\nMotif $patternText found at position $-[0]\n";
}
sub displayPrompt
{
while(not defined($patternFile))
{
$testFile = getInput("Please enter a motif pattern file.\n\t");
if(-f $testFile)
{
$patternFile = $testFile;
}
else
{
printf "\n\"$testFile\" does not exist in the current directory.\n"
}
}
while(not defined($searchFile))
{
$testFile = getInput("Please enter a sequence file.\n\t");
if(-f $testFile)
{
$searchFile = $testFile;
}
else
{
printf "\n\"$testFile\" does not exist in the current directory.\n"
}
}
}
sub getInput
{
my $prompt = shift;
$prompt = "" if not defined $prompt;
$files = "";
if(defined($patternFile))
{
$files = "\Motif pattern file: " . $patternFile . "\n";
}
else
{
$files = "\Motif pattern file: NONE\n";
}
if(defined($searchFile))
{
$files = $files . "Sequence file: " . $patternFile . "\n";
}
else
{
$files = $files . "Sequence file: NONE\n";
}
$prompt = $files . $prompt;
print($prompt);
$input = <>;
chomp($input);
return $input;
}
sub readFile
{
my $file = shift;
print "\nRead from file " . $file;
if(not -f $file)
{
printf "\n$file is not a valid file in the current directory.\n";
exit;
}
$text = "";
if (open(my $fh, '<:encoding(UTF-8)', $file))
{
while(my $line = <$fh>)
{
# DO NOT USE
# if(not eof)
# WILL NOT READ LAST LINE
chomp $line;
$text = $text . uc($line); # Uppercase
}
}
else
{
print "\nError reading file: " . $file;
}
return $text;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment