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


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

Hello and Welcome to Perl and the Monastery, mizducky!

You are storing the length of the @colors array in the variable $count, but then modifying the length of the array by using splice to remove elements. So, because you are reducing the length of the array from 7 down to 5, and you are still trying to access elements from the original length of the array, which now no longer exist, you're getting the warning "Use of uninitialized value in string eq".

By the way, the more Perlish way to iterate over the indicies of an array is for my $num (0..$#colors), where $#colors returns the index of the last element of the array.

Note that your code suffers from an issue: If the two colors to be removed are immediately after one another in @colors, only one will be removed. Can you see why that is? If you're not sure, see the Basic debugging checklist: something as simple as printing the values of the variables as your loop runs will already give you a lot of information.

Personally, when I have to modify an array I am iterating over, I like to use a classic for (my $i=0; $i<@array; $i++) loop, because if I am inserting or removing elements, that form gives me the most control over $i, which I may have to modify depending on where I'm inserting/removing elements. If that gets too complicated, note that in Perl, There Is More Than One Way To Do It. Unless your homework assignment explicitly states that you should iterate over the looparray this way, here are some ideas:

Another limitation of your code is that it only works for the case of @drop having two elements - this could also be solved in a few different ways: