我希望用子程序从一些大数组中删除元素。为了避免在子程序中进行拷贝,我使用引用。
@a=qw(ok now what is hi the matter);
sub zonk {
$array=shift; # this is a reference of an array
foreach $i (0..$#$array) { # I saw some say to avoid last element to get size
#if (@$array[$i] =~ /hi/) { delete @$array[$i]; }
#if ($array->[$i] =~ /hi/) { delete $array->[$i]; }
#if ($array->[$i] =~ /hi/) { delete @$array->[$i]; }
if ($array->[$i] =~ /hi/) { print "FOUND "; }
print $array->[$i],"\n";
}
@$array = grep{$_} @$array; # removes empty elements
}
zonk(\@a);
print join(':',@a);
如果我按照原样运行上述程序,会得到以下结果:
ok
now
what
is
FOUND hi
the
matter
ok:now:what:is:hi:the:matter
但是如果我使用任何被注释掉的行,我会得到以下错误:
delete argument is not a HASH element or slice at hi.pl line 10.
我最初尝试使用splice,但是索引在变化,使迭代混乱。 很高兴能够知道本帖中提到的所有方法,但是我正在寻找最有效的方法:)
补充说明:这在我的Linux机器上完美地运作(Ubuntu 9.10,Perl 5.10),但在我的Windows 7工作机器上使用Perl 5.005_03时出现了上述错误。 升级不是一个选项。
谢谢