首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从Perl中少于15个字符的字符串中获取15个字符

从Perl中少于15个字符的字符串中获取15个字符
EN

Stack Overflow用户
提问于 2014-03-16 06:06:08
回答 2查看 77关注 0票数 0

我有一个序列和一个表示残差(字符)位置的数字。我想从残留物的两边各取7个残留物。下面是实现这一点的代码:

代码语言:javascript
复制
my $seq = substr($sequence, $location-8, 14);

这从残留物的两边各抓取7个。然而,有些序列两边的残基都少于7个。因此,当发生这种情况时,我会收到一个错误消息:

代码语言:javascript
复制
substr outside of string at test9.pl line 52 (#1) (W substr)(F) You tried to reference a substr() that pointed outside of a string.  That is, the absolute value of the offset was larger than the length of the string.

如何更改空白处,并用另一个字母(例如X)替换它们?

例如,如果有一个序列ABCDEFGH,并且$location指向D,那么我需要在两边各有7个,因此结果将是: XXXXABCDEFGHXXX

EN

回答 2

Stack Overflow用户

发布于 2014-03-16 06:32:05

对我上面的评论进行扩展。我将创建一个my_substr函数来封装填充和位置移位。

代码语言:javascript
复制
my $sequence = "ABCDEFGH";
my $location = 3;

sub my_substr {
 my ($seq, $location, $pad_length) = @_;
 my $pad = "X"x$pad_length;
 return substr("$pad$seq$pad", $location, (2*$pad_length+1));
}

print my_substr($sequence, $location, 7) . "\n";

收益率

代码语言:javascript
复制
XXXXABCDEFGHXXX
票数 2
EN

Stack Overflow用户

发布于 2014-03-16 06:20:08

这是一个非常冗长的答案,但或多或少会得到你想要的:

代码语言:javascript
复制
use strict;
use warnings;

my $sequence = 'ABCDEFGH';
my $wings = 7;

my $location = index $sequence, 'D';
die "D not found" if $location == -1;

my $start = $location - $wings;
my $length = 1 + 2 * $wings;

my $leftpad = 0;
if ($start < 0) {
    $leftpad = -1 * $start;
    $start = 0;
}
my $seq = substr($sequence, $start, $length);
$seq = ('X' x $leftpad) . $seq if $leftpad;

my $rightpad = $length - length ($seq);
$seq .= 'X' x $rightpad if $rightpad > 0;

print $seq;

或者为了避免所有额外的工作,可以只创建一个包含padding的新$sequence变量:

代码语言:javascript
复制
my $sequence = 'ABCDEFGH';
my $wings = 7;

my $location = index $sequence, 'D';
die "D not found" if $location == -1;

my $paddedseq = ('X' x $wings) . $sequence . ('X' x $wings);
my $seq = substr($paddedseq, $location, 1 + 2 * $wings);

print $seq;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22430347

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档