On Thu, 26 Feb 2009, Barry Brevik wrote:
> 
> Often I will test some base-level part of a Perl routine I am writing,
> even if it is something I already know, just to make sure it really
> works as expected. I find that this makes later debugging easier.
> 
> Anyway, I need to count how many 'records' I have in a hash after my
> program gets done stuffing values into it. So I wrote a piece of test
> code that goes like this:
> ------------------------
> use warnings;
> 
> %parts = {};
> 
> $parts{'ms51957-101'} = 1207;
> $parts{'ms51957-102'} = 17;
> $parts{'ms51957-103'} = 1;
> 
> print "Number of Records in hash: ", scalar keys %parts, "\n";
> 
> Number of Records in hash: 4
> ------------------------
> 
> To my surprise, this is wrong; there are only 3 records in the hash.


Didn't you get a warning from the program, something like " Reference
found where even-sized list expected"?
 
> NOW for the weird part. On a hunch, I changed the line:
> 
>     %parts = {};

This is the same as

      %parts = ({}, undef);

Which creates a single hash element that has the stringified version of a hash
reference, e.g. "HASH(0x239bac)" and a value of undef.

> ...to...
> 
>     %parts = ();
> 
> Now I get:
> 
>   Number of Records in hash: 3
> 
> ...which is correct. Anyone out there know what gives?? And which is the
> "correct" way to define an empty hash, {} or ()?

() is an empty list, {} is a reference to an anonymous empty hash.

Cheers,
-Jan

_______________________________________________
ActivePerl mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs

Reply via email to