One way
use warnings;
use strict;
use feature 'say';
my $string;
# Read submitted files line by line (or STDIN if @ARGV is empty)
while (<>) {
chomp;
$string = $_;
last; # just in case, as we need ONE line
}
# $string = q(abcdefghijklmnopqrstuvwxyz); # test
my $padding = 3; # for the given test sample
my @patterns = do {
my $search_file = 'search.txt';
open my $fh, '<', $search_file or die "Can't open $search_file: $!";
<$fh>;
};
chomp @patterns;
# my @patterns = qw(bcd fgh pqr uvw); # test
foreach my $patt (@patterns) {
if ( $string =~ m/(.{0,$padding}) ($patt) (.{0,$padding})/x ) {
say "$1\t$2\t$3";
# or
# printf "%-3s\t%3s%3s\n", $1, $2, $3;
}
}
Run as program.pl seq.txt
, or pipe the content of seq.txt
to it.†
The pattern .{0,$padding}
matches any character (.
), up to $padding
times (3
above), what I used in case the pattern $patt
is found at a position closer to the beginning of the string than $padding
(like the first one, bcd
, that I added to the example provided in the question). The same goes for the padding after the $patt
.
In your problem then replace $padding
to 100
. With the 100
wide "padding" before and after each pattern, when a pattern is found at a position closer to the beginning than the 100 then the desired \t
alignment could break, if the position is lesser than 100 by more than the tab value (typically 8).
That's what the line with the formatted print (printf
) is for, to ensure the width of each field regardless of the length of the string being printed. (It is commented out since we are told that no pattern ever gets into the first or last 100 chars.)
If there is indeed never a chance that a matched pattern breaches the first or the last 100 positions then the regex can be simplified to
/(.{$padding}) ($patt) (.{$padding})/x
Note that if a $patt
is within the first/last $padding
chars then this just won't match.
The program starts the regex engine for each of @patterns
, what in principle may raise performance issues (not for one run with the tiny number of 4000 patterns, but such requirements tend to change and generally grow). But this is by far the simplest way to go since
we have no clue how the patterns may be distributed in the string, and
one match may be inside the 100-char buffer of another (we aren't told otherwise)
If there is a performance problem with this approach please update.
† The input (and output) of the program can be organized in a better way using named command-line arguments via Getopt::Long
, for an invocation like
program.pl --sequence seq.txt --search search.txt --padding 100
where each argument may be optional here, with defaults set in the file, and argument names may be shortened and/or given additional names, etc. Let me know if that is of interest
seq.txt
is just one line?