This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Bioperl printing part of sequence using subseq()

Hello, I want to apply following function on a file which has thousands of sequences. I want to print 192 residues after it finds a motif at position $pos.

print $seq_obj->subseq($pos+1,$pos+192), "\n";

Now problem is that sometimes sequence length is short than 192 residues and it resulted in error. Can anybody help me to find the possible solution? I like the sequence to be printed even if it is shorter than 192 residues. Thanks. Reaz

bioperl

Hi Chris, Thanks. Actually I need to print only 192 residues after motif not the complete sequence. I will be OK if my subseq ignores those sequences which are shorter than 192 residues.

See modified answer below.

4 answers

You need to extract up to 192 bases after the motif without going outside the bounds. You would still need to use the length() method, but to clarify the code a bit break out the coordinates into specific variables and basically do a ternary check to pick the right end, something like:

my $len = $seq->length;
my $start = $pos + 1;
my $end = ($pos + 192) < $len ? $pos + 192 : $len;
print $seq_obj->subseq($start,$end), "\n";

I assign the length to a variable to avoid running two method calls, which can add up depending on how many times you will run this.

Original Reply:

Check the length of the sequence, and if it's shorter than 192 residues then simply print it and not the subseq.

EDIT: clarified a tad bit more.

EDIT2: Modified answer to address respondent's question after they clarified the intent.

Use List::Util qw(min) and replace 192 with min($seq_obj->length, 192).

Hello Chris, This ternary check seems to solve my problem. Thanks I appreciate.

Hi riaasuddin , just to make sure it's clear, you should then accept that answer as correct for others to note.

Yes I confirm that the ternary check solved my problem.

Log in to answer this question.