http://www.perlmonks.org?node_id=11104794


in reply to The error says the value is uninitialized, but it works anyway

The code uses splice to remove the elements from the array but the size of the array is not adjusted in the foreach loop. Below code would traverse the array based on the last index of the array. This works even after using warnings module without any error. Here I am adjusting the for loop count based on your splice.

use warnings; print "hello world\n"; my @colors = qw(red green blue yellow pink purple brown); my @drop = qw(pink brown); my $num = 0; for (0..$#colors){ if ($colors[$num] eq $drop[0] or $colors[$num] eq $drop[1]){ + splice (@colors, $num, 1); $num--; } $num++; } print "@colors \n";

Replies are listed 'Best First'.
Re^2: The error says the value is uninitialized, but it works anyway
by soonix (Canon) on Aug 21, 2019 at 13:02 UTC
    if ($colors[$num] eq $drop[0] or $colors[$num] eq $drop[1]){ + splice (@colors, $num, 1); $num--; } $num++;
    Just as a nitpick: I think it's better to
    if ($colors[$num] eq $drop[0] or $colors[$num] eq $drop[1]) { splice (@colors, $num, 1); } else { $num++; }
    because find it's somehow dopey (for lack of a better word) to decrement just to increment immediately afterwards.
    With "else" it's clear that you need to increment only if the condition isn't met.