user2815290
user2815290

Reputation: 31

How to get around the scope of the foreach loop in Perl

So I'm working through a bit of code that my compiler really doesn't like. There are two arrays, that have an identical number of indexes. @array is populated with 0's, @otherarray is populated sequentially. In this foreach loop, it skips over the first value because it is filled outside the loop. Count is declared as 1 outside the loop as well.

foreach (@array) {
    if ($count == 1) {
    } elsif($_ == 0 && @otherarray[$count-1] != undef) {
        $_ = $count;
        splice(@otherarray, @otherarray[$count - 1], 1);
    } else {
        $_ = $otherarray[ rand @otherarray ];
    }
$count++
}

It insists that I have use of uninitialized value in numeric ne(!=) on this line, and every line in which other array is inside an else/if/elsif statement:

elsif($_ == 0 && @otherarray[$count-1] != undef) 

How do I work around this? I'm sure it's obvious but I'm really new to Perl, so I'm probably setting something up wrong in the first place? I have already declared my @otherarray.

Upvotes: 3

Views: 124

Answers (1)

RobEarl
RobEarl

Reputation: 7912

It is the undef in the comparison which is uninitialized. Use defined instead of comparing to undef:

elsif($_ == 0 && defined($otherarray[$count-1]))

Upvotes: 4

Related Questions