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

前端之家收集整理的这篇文章主要介绍了使用引用指向Perl中的滑动窗口数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是我的问题:我有2个数组.一个是字符数组,表示一个滑动窗口.字符从头开始移动并在结尾处推送.我想使用第二个数组来存储对数组切片的引用,这些数组切片在它们移动时“跟随”字符.例:

my @char_array = ('h','e','l','o','w','r','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;

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

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

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

解决方法

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

const char* s = str+1;
const char* e = str+len;
for (const char* p=s; p!=e; ++p) putc(*p);

除了指针算法不允许你调整缓冲区的大小(推@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,length($char_array));
say substr($char_array,$s,$e-$s+1);    # elloworld
$char_array =~ s/^.//s;
$char_array .= 'x';
say substr($char_array,$e-$s+1);    # lloworldx

事实上,如果我们真的在谈论字符,我们很幸运,因为我们可以使用左值子系统让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更容易,或多或少都有相同的好处!

猜你在找的Perl相关文章