在Perl中将字母添加到数组的最后一个元素

时间:2012-09-12 08:12:54

标签: arrays perl element

下面给出的脚本会在每次出现“E”时剪切输入字符串并将其存储在数组中。最终输出显示“E”的每个位置的所有碎片字符串。但问题是,这个脚本在输出中的数组的最后一个元素中没有显示任何“E”,它只显示“D”。我得到的输出是 -

ABCDEABCDE ABCDE ABCDE ABCD
ABCDE ABCDEABCDE ABCDE ABCD
ABCDE ABCDE ABCDEABCDE ABCD
ABCDE ABCDE ABCDE ABCDEABCD
ABCDE ABCDE ABCDE ABCDE ABCD

但我想要的最终输出是 -

ABCDEABCDE ABCDE ABCDE ABCDE
ABCDE ABCDEABCDE ABCDE ABCDE
ABCDE ABCDE ABCDEABCDE ABCDE
ABCDE ABCDE ABCDE ABCDEABCDE
ABCDE ABCDE ABCDE ABCDE ABCDE

我的剧本是 -

my $s = 'ABCDEABCDEABCDEABCDEABCDE';
if (substr($s,-1) eq "E") {
    @array1 = @array[0 .. $#array-1];
    print "Results of 1-missed cleavage having 1E at the end\n\n";
    for my $array1 (@array1) {
        substr($s, $array1-1, 1) = "\0";
        my @a = split(/E(?!P)/, $s);
        substr($s, $array1-1, 1) = 'E';
        $_ =~ s/\0/E/g foreach (@a);
        $result = join ("E,", @a); 
        @final = split(/,/, $result);
        print "@final\n";
    }
    my @output=split(/E(?!P)/, $s);
    $out = join ("E,", @output); 
    @output1 = split(/,/, $out);
    print "@output1\n\n";
}
else {
    print "E is not at terminal position"
};

1 个答案:

答案 0 :(得分:1)

考虑更简单一点?

my $s = 'ABCDEABCDEABCDEABCDEABCDE';

# Split on "E not followed by whitespace".
# Replace with "E<space><matched char, if any>"
$s =~ s/E([^\s]?)/E \1/g;

print $s, "\n\n";

输出:

haiku:~$ perl blah.pl 
ABCDE ABCDE ABCDE ABCDE ABCDE 

haiku:~$

Perl是一个非常强大的文本操作工具,它的正则表达式是首屈一指的(恕我直言)。