tags:

views:

199

answers:

1

What is difference between if (%hash) and if (defined %hash)?

my %hash ;

if ( %hash) { 

  print "defined "; 
}

if (defined %hash)  { 
  print "defined ";
}
+22  A: 

From perldoc -f 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"   }
eugene y
Before 5.8.3 there was a problem with tied hashes in scalar context. They would usually return 0. If you're writing code for pre-5.8.3 use `if( keys %hash )` http://perldoc.perl.org/perl583delta.html#Core-Enhancements
Schwern