http://qs321.pair.com?node_id=581668


in reply to Why "use of uninitialized value" warning comes?

This warning seems quite clear to me. It says that you are doing a string comparison with an undefined value. You are only doing one string comparison in this code (and I assume that's on line 9). The comparison looks like this:

$need[$incr] eq ''

The empty string isn't undefined, so it must be that the value in $need[$incr] becomes undefined at some point. This is almost certainly caused by your unconventional looping mechanism. I think that you think that once you go past the end of the @need array then your string comparison will be true and your loop will exit. And that is what is happening, but when you go past the end of an array, the next (non-existant) element is "undef", not the empty string. Now, in a string comparison, "undef" is converted to the empty string, but that conversion isn't silent and you'll get that warning to tell you what Perl has done.

To avoid the warning, check that $needs[$incr] is defined, not that it is an empty string. Actually this whole approach is a little fragile as an array can contain undefined elements (and empty strings) and your loop could finish early. You might be better off using a foreach loop to iterate across the array.

Perl's warning and error messages are generally far clearer that the ones that you get from many other languages. If you read them carefully then you can usually work out what they are trying to tell you. If you need more help, then look at the perldiag manual page or add use diagnostics to your program (but remove it again once the program is finished).

--
<http://dave.org.uk>

"The first rule of Perl club is you do not talk about Perl club."
-- Chip Salzenberg