简体   繁体   中英

perl quits loop early

my program has 2 variables in the target_services array

DB<1> x @target_services
0  3400000000000012
1  3400000000000011

this is the code it hits

 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++;
    }

the debugger implies that it goes through the loop once, gets to the next; and then jumps to my print statement. and never goes through the loop a second time.

please explain why this is

It's documented in perlsyn :

If any part of LIST is an array, foreach will get very confused if you add or remove elements within the loop body, for example with splice . So don't do that.

That's exactly what you did:

foreach my $i (@target_services){
    # ...
    my $ts_id  = shift @target_services;

Instead use

foreach my $ts_id (@target_services){
    # ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM