perl早退出循环

yan*_*kel 0 perl loops

我的程序在target_services数组中有2个变量

DB<1> x @target_services
0  3400000000000012
1  3400000000000011
Run Code Online (Sandbox Code Playgroud)

这是它命中的代码

 foreach my $i (@target_services){
        my $vl    = shift @values  || "";
        my $dp    = shift @descriptions || "";
        my $ts_id  = shift @target_services;
        my $lp    = shift @lp_values;
        if (get_lp($ts_id,$lp) eq 'YES'){
            print "ts id $ts_id already has $lp LP. Aborting addition of this LP for this TS\n";
            next;
        }
        my $temp_query = $sql3;
        $temp_query =~ s/TS/$ts_id/;
        $temp_query =~ s/LP/$lp/;
        $temp_query =~ s/VL/$vl/;
        $temp_query =~ s/DP/$dp/;
        my $sth3 = get_sth($temp_query);
        $count_lps+=$sth3->get_count();
        $count_ts++;
    }
Run Code Online (Sandbox Code Playgroud)

调试器暗示它经过循环一次,到达下一个; 然后跳到我的打印声明.并且永远不会再次通过循环.

请解释为什么会这样

cho*_*oba 8

它在perlsyn中有记录:

如果LIST的任何部分是一个数组,foreach如果你在循环体中添加或删除元素,将会非常困惑,例如splice.所以不要这样做.

这正是你所做的:

foreach my $i (@target_services){
    # ...
    my $ts_id  = shift @target_services;
Run Code Online (Sandbox Code Playgroud)

而是使用

foreach my $ts_id (@target_services){
    # ...
Run Code Online (Sandbox Code Playgroud)