使用引用指向Perl中的滑动窗口数组

Asc*_*ari 3 perl reference slice character-arrays

这是我的问题:我有2个数组.一个是字符数组,表示一个滑动窗口.字符从头开始移动并在结尾处推送.我想使用第二个数组来存储对数组切片的引用,这些数组切片在它们移动时"跟随"字符.例:

my @char_array = ('h','e','l','l','o','w','o','r','l','d');
my $char_arr_ref=[@char_array[1..$#char_array]]; 
print @$char_arr_ref, "\n"; # slice contains 'elloworld';
shift(@char_array);
push(@char_array), 'x';
print @$char_arr_ref, "\n"; # slice still contains 'elloworld', not 'lloworldx' as I need;
Run Code Online (Sandbox Code Playgroud)

换句话说,我希望能够使用第二个数组引用数组切片(例如我在C中使用指针数组).

在Perl中有这样的惯用方法吗?

更新:这是进行快速文本搜索的大型程序的一部分.我打算使用一个引用的哈希(比如说,而不是'index'函数,它很慢.我需要在Perl中执行此操作.

ike*_*ami 8

在C中,您的窗口可能使用指针算法实现.

const char* s = str+1;
const char* e = str+len;
for (const char* p=s; p!=e; ++p) putc(*p);
Run Code Online (Sandbox Code Playgroud)

指针运算不允许您调整缓冲区(push @char_array, 'x';)的大小.即使在C中,你也必须使用偏移量.

size_t si = 1;
size_t ei = len;
for (size_t i=si; i!=e1; ++i) putc(str[i]);
Run Code Online (Sandbox Code Playgroud)

这很幸运,因为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
Run Code Online (Sandbox Code Playgroud)

如果我们真的在谈论字符,那么字符串会更有效率.

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
Run Code Online (Sandbox Code Playgroud)

事实上,如果我们真的在谈论字符,我们很幸运,因为我们可以使用左值子系统让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
Run Code Online (Sandbox Code Playgroud)

方式比C更容易,或多或少都有相同的好处!