在perl中,splice在循环中运行良好

时间:2014-07-16 14:22:30

标签: perl

我想了解拼接。 我想使用splice逐个删除数组中的所有元素。但我得到的输出仍然很奇怪。我无法理解它。有人可以解释一下:

代码

my @arr1=(1,2,3,4,5,6,7,8,9,10);

foreach my $num(@arr1)
{
    print $_ foreach (@arr1);
    print "\n Popping $num\n";
    print "[0] is $arr1[0] and current element is $num \n";
    splice @arr1,0,1;
    print "\n";
}

输出:

 12345678910
 Popping 1
[0] is 1 and current element is 1

2345678910
 Popping 3
[0] is 2 and current element is 3

345678910
 Popping 5
[0] is 3 and current element is 5

45678910
 Popping 7
[0] is 4 and current element is 7

5678910
 Popping 9
[0] is 5 and current element is 9

3 个答案:

答案 0 :(得分:3)

foreach创建原始10个数组元素的列表。您应该使用while来修改数组。

use warnings;
use strict;

my @arr1=(1,2,3,4,5,6,7,8,9,10);

while (@arr1)
{
    my $num = $arr1[0];
    print $_ foreach (@arr1);
    print "\n Popping $num\n";
    print "[0] is $arr1[0] and current element is $num \n";
    splice @arr1,0,1;
    print "\n";
}

答案 1 :(得分:2)

你正在循环通过它来改变数组。 foreach从[0]到[1]到[2]形式。当你拼接[0]时,它会转到[1]这是原始的[2]。当你拼接了它时,它会转到[2],现在它是原始的[4],因为你已经取走了第一个。

希望能稍微清理一下。

你可以避免使用@ arr1作为循环控制器:

my @arr1=(1,2,3,4,5,6,7,8,9,10);

my $max = @arr1;
for (my $i=0; $i<$max; $i++) {
    print $_ foreach (@arr1);
    my $num = splice @arr1,0,1;
    print "\n Popping $num\n";
    print "[0] is $arr1[0] and current element is $num \n";
    print "\n";
}

答案 2 :(得分:2)

不要修改使用foreach迭代的数组。

通常,解决方案通常为grep。例如,以下处理@todo中的元素,留下在数组中处理失败的元素。

sub process {
   ...
   return 0 if error;
   ...
   return 1;
}

@todo = grep { !process($_) } @todo;

在这种情况下,请将foreach替换为while

my @queue = 1..10;

while (@queue) {
   my $num = shift(@queue);
   print "Current element is $num\n";
}