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

来源:百度知道 编辑:UC知道 时间:2024/05/27 02:54:26
这个程序很简单,查找一个小字符串在大串里面出现的所有位置。
#!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
Foun