Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Why "use of uninitialized value" warning comes?

by davorg (Chancellor)
on Nov 01, 2006 at 12:44 UTC ( #581668=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://581668]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2022-08-09 00:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?