这个perl小程序为什么耗尽内存??

这个程序很简单,查找一个小字符串在大串里面出现的所有位置。#!usr/local/bin/perl-wusestrict;use5.010;my$big="Thisist... 这个程序很简单,查找一个小字符串在大串里面出现的所有位置。
#!usr/local/bin/perl -w
use strict;
use 5.010;

my $big="This is true";
my $small="is";
my @where;
my $wh=0;
while($wh!=-1)
{
push @where, $wh;
$wh=index(substr($big,$wh),$small);
}
shift @where;#get rid of 0!
if(@where)
{say "Found $small in $big at position(s):".@where;}
else
{say "Nowhere found!";}

运行之后电脑死机,过后显示“out of memory"。
展开
 我来答
PyQt
2009-08-25 · TA获得超过350个赞
知道小有建树答主
回答量:83
采纳率:100%
帮助的人:90.4万
展开全部
把你的程序稍作修改你就知道为什么了
#!perl -w
use strict;

my $big="This is true";
my $small="is";
my @where;
my $wh=0;
my $n = 10;
while($n--)
{
push @where, $wh;
my $sub = substr($big,$wh);
print "$n: substr:$sub";

$wh=index($sub, $small);
print "\tindex: $wh\n";
}

shift @where;#get rid of 0!
if(@where) {
print "Found $small in $big at position(s): @where\n";
} else {
print "Nowhere found!\n";
}

这是打印的结果:
9: substr:This is true index: 2
8: substr:is is true index: 0
7: substr:This is true index: 2
6: substr:is is true index: 0
5: substr:This is true index: 2
4: substr:is is true index: 0
3: substr:This is true index: 2
2: substr:is is true index: 0
1: substr:This is true index: 2
0: substr:is is true index: 0
Found is in This is true at position(s): 2 0 2 0 2 0 2 0 2

第一次在$big中substr返回整个$big,找到"is"的位置为2,此时$wh=2;
第二次substr得到"is is true",找到"is"的位置为0,此时$wh=2;
第三次,问题出现了,substr操作的字符串是$big,$wh为0,所以substr操作返回整个big,找到"is"的位置为2.....
如此循环往复,陷入死循环,当然会内存溢出啦~~
简单的修改下你的程序就ok了
#!perl -w
use strict;

my $big="This is true";
my $small="is";
my @where;
my $wh = 0;

while(1)
{
$wh = index($big, $small, $wh);
last if $wh==-1;
push @where, $wh;
$wh++ ;
}
if(@where) {
print "Found $small in $big at position(s): @where\n";
} else {
print "Nowhere found!\n";
}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式