Geek Challenge: undef the perl code

So after yesterday's GC (geek challenge) a friend sent along the following.
#!/bin/perl

#Debug
print $foo->{bar}->{baz};

if ( exists $foo->{'bar'} ) {
        print "def"
} else {
        print "undef"
}

But it always prints def - why?

For what it's worth.

Update: I have updated the code snip... sorry I had the wrong code block in there before.

Comments:

because you are doing "exists" not "defined" ?

Posted by alecm on March 15, 2005 at 11:22 AM EST #

oops - that is the answer to the RSS version of this posting, attached below. The one above defines $foo->{bar} to be an anonymous hash containing one element, indexed by baz, so is not empty. "Exists" will return true, accordingly.

#perl $foo{bar} = undef; #Debug; print $foo{bar}; if(exists $foo{bar}) { print "undef"; } else { print "def"; }

Posted by alecm on March 15, 2005 at 11:28 AM EST #

So the answer is that the #Debug statement defines the hash for debugging. So w/o the #Debug statement in there the code would operate as one would think is should.

Posted by Dan Lacher on March 17, 2005 at 08:20 AM EST #

Post a Comment:
Comments are closed for this entry.
About

dlacher

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today