in reply to Predeclaration

I learned something today. I thought that with my @x; @x would be undefined but with my @x = (); @x would be a defined but empty list. I guess I was wrong. Here is the experiment I ran. I
my @x; print 'my @x;',"\n"; &checkdef; @x = (); print '@x = ();',"\n"; &checkdef; @x = (1); print '@x = (1);',"\n"; &checkdef; @x = (); print '@x = ();',"\n"; &checkdef; undef @x; print 'undef @x;',"\n"; &checkdef; @x = (); print '@x = ();',"\n"; &checkdef; sub checkdef { if (defined (@x)) { print "\@x is defined\n" } else { print "\@x is undefined\n" } } __OUTPUT__ my @x; @x is undefined @x = (); @x is undefined @x = (1); @x is defined @x = (); @x is defined undef @x; @x is undefined @x = (); @x is undefined

Is anyone else surprised by the results?

--

flounder

Replies are listed 'Best First'.
Re: Predeclaration
by Abigail-II (Bishop) on Jul 16, 2002 at 14:49 UTC
    Is anyone else surprised by the results?
    People who read the manual pages will not be surprised. From the manual page about defined:
                   Use of "defined" on aggregates (hashes and arrays)
                   is deprecated.  It used to report whether memory
                   for that aggregate has ever been allocated.  This
                   behavior may disappear in future versions of Perl.
                   You should instead use a simple test for size:
    
                       if (@an_array) { print "has array elements\n" }
                       if (%a_hash)   { print "has hash members\n"   }
    

    Abigail

      Damn documentation! Another case of what I think it does vs. what it really does (and is documented) DWIMing has me spoiled. I think perl's ability to read my mind needs improving! Larry needs to take some lessons from Miss Cleo! (Or at least the acress who plays her)

      --

      flounder

      ps. For those of you outside the USA (or who never turned on a TV after 11pm in the US) Miss Cleo was a (so called) psychic with a bad fake Jamacan accent who pushed a psychic hotline. The actress who played her recently appeared in court and admitted she was not Jamacan during a fraud investigation.