Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Defined vs. undefined

by xdg (Monsignor)
on Feb 10, 2006 at 12:15 UTC ( [id://529339]=note: print w/replies, xml ) Need Help??


in reply to Defined vs. undefined

The real issue you have is that when the hash is empty, @keyarr gets no values from keys %hash. Thus, $keyarr[0] is undefined, causing the warning.

However, when the hash is not empty, @keyarr has values, so $keyarr[0] is defined and doesn't trigger the warning.

Add a print statement to show what's in @keyarr and then it may be clearer to you what is happening.

my (%hash); #my (%hash) = ( foo => 'bar' ); # Try this variation my (@keyarr)=(keys (%hash)); print "keys: '@keyarr'\n"; # Add this line if (defined ($hash{$keyarr[0]})) {print "hash is defined\n";} else {print "hash is undefined\n";}

-xdg

Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

Replies are listed 'Best First'.
Re^2: Defined vs. undefined
by misterb101 (Sexton) on Feb 10, 2006 at 15:57 UTC
    xdg, you're right, but then the question is why one would use a variable that is potentially undefined??
    for this, testing whether the hash has values is better like in muntfish's solution.
    But if you go that route, why don't you directly test if (scalar(%hash)!=0) { ....??
    using a hash in scalar context gives 0 for a empty hash and the number of used entries for a nonempty hash.
    my %hash = (1=>2,3=>4);print "scalarval=".scalar(%hash); => 2/8

    Cheers,
    Rob
      xdg, you're right, but...

      I didn't recommending that approach. I just answered the original question. Sometimes a limited answer is the one that people need in order to make their own discoveries. (See "Baby" Perl versus "Bad" Perl.)

      -xdg

      Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2024-03-29 02:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found