在 C 中,您的窗口可能是使用指针算术来实现的。
const char* s = str+1;
const char* e = str+len;
for (const char* p=s; p!=e; ++p) putc(*p);
除了指针算术不允许您调整缓冲区的大小(push @char_array, 'x';
)。即使在 C 语言中,您也必须使用偏移量。
size_t si = 1;
size_t ei = len;
for (size_t i=si; i!=e1; ++i) putc(str[i]);
这是幸运的,因为 Perl 没有指针,更不用说指针运算了。但抵消呢?没问题!
my @char_array = split //, 'helloworld';
my ($s, $e) = (1, $#char_array);
say @char_array[$s..$e]; # elloworld
shift @char_array;
push @char_array, 'x';
say @char_array[$s..$e]; # lloworldx
如果我们实际上讨论的是字符,那么字符串会更有效。
my $char_array = 'helloworld';
my ($s, $e) = (1, length($char_array));
say substr($char_array, $s, $e-$s+1); # elloworld
$char_array =~ s/^.//s;
$char_array .= 'x';
say substr($char_array, $s, $e-$s+1); # lloworldx
事实上,如果我们实际上谈论的是字符,我们非常幸运,因为我们可以使用左值 substr 并让 Perl 为我们处理偏移量!
my $char_array = 'helloworld';
my $substr_ref = \substr($char_array, 1, length($char_array)-1);
say $$substr_ref; # elloworld
$char_array =~ s/^.//s;
$char_array .= 'x';
say $$substr_ref; # lloworldx
比 C 更容易,并且具有或多或少相同的好处!