数组 – 如何删除引用数组的元素?
我想用一个子程序从几个大数组中删除元素.我使用引用来避免副本进入子.
@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参数不是hi.pl第10行的HASH元素或切片. 我最初尝试拼接,但随后指数正在转移并混淆了迭代. 附录:这在我的linux机器上是完美的(我的意思是每条注释行)(ubuntu 9.10,perl 5.10),但上面的错误是在工作时使用perl 5.005_03在我的Windows 7盒子上. 谢谢 解决方法
为什么不从一开始就贪图?
@array = grep { !/hi/ } @array; # Or,for *referenced* array @$arrayRef = grep { !/hi/ } @$arrayRef; 一小组注释,用于澄清评论中出现的问题: >此方法(或使用grep包括原始海报代码的任何方法)将通过新结果数组的大小增加脚本的内存使用量. 例如.如果脚本(没有第一个阵列)占用10MB内存,原始阵列需要15MB内存,结果阵列占用14MB内存,那么当grep运行时,程序的总内存占用将从25MB增加到39MB . (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |