永发信息网

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

答案:2  悬赏:50  手机版
解决时间 2021-02-17 20:50
这个程序很简单,查找一个小字符串在大串里面出现的所有位置。
#!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"。
最佳答案
把你的程序稍作修改你就知道为什么了
#!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";
}
全部回答
没看懂什么意思?
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
【you will realize怎么翻译?】
颁奖时拿错奖杯怎么办
我遇到一点小事就很紧张,所以现在说话很快,
运动会3000米加油稿
奥特曼格斗进化重生中谁最厉害
-根号19÷根号95等于多少 急!在线等、要具体
同事们组织一起活动,我不喜欢,比如KTV等,
弯腰时后腰疼痛和两侧酸胀是怎么回事啊!
陕西咸阳 乾县 地区的经济状况怎么样? 跟其
美少女的谎言第三季第二十集插曲
在小县城摆地摊卖什么比较好?
【dear friends(亲爱的朋友)里面 跳舞DJ曲的
寿光市文家街道吕家庄村民委员会在什么地方啊
河源超市几点关门?
Are you in the street about the matter?【
推荐资讯
如何制作炸丸子工具
月经干净10天能取环吗?
宛城区南阳德高防水(范蠡东路)怎么去啊,谁知
【现在市场什么需求量大】现在市场上商品的数
《噢.必胜奉顺英》中的卢郁婷是谁扮演的
为什么部分充电宝无法给iphone5充电,应该这
旭影美术学校地址在什么地方,我要处理点事!
如果某电视频道播出被国家广电总局禁播的电视
植物大战僵尸2天空之城第16关怎么三星通关
成语四什么三什么
心血是什么意思
根据IPL5上的表现,大家觉得WE能拿下英雄联盟
正方形一边上任一点到这个正方形两条对角线的
阴历怎么看 ?