in reply to Hash problem
I am definitely no expert on this, but my understanding is that the problem here has to do with context. The idea is that expressions return different values depending on their context. In list context, expressions are expected to return lists. In scalar context, expressions are expected to return scalars. In list context (which is what you've got without the "\n".), you get a list of keys and values which get printed like any list of things passed to print. In scalar context (which is what you get with the concatenation), you get 2/8, where 2 is the number of items currently in the hash table and 8 is the number of buckets in the hash table.(1) (It's basically telling you the current load factor. If "load factor" and "buckets" don't make sense, read up on hash tables... Wikipedia's article isn't so bad for a start.)
Concatenation forces an expression forces the expression into scalar context. It's that scalar contextualness (1) that forces the hash into producing the 2/8. (2) Note that:
my %newHash = ("key1","value1","key2","value2"); print scalar %newHash; //scalar method forces scalar context
also prints:
2/8
Bibliography (aka "Stuff I n00bishly read in trying to compose this answer"):
-http://perl.plover.com/context.html
-NEVER a list in a scalar context -- PLEASE!
-http://www.itworld.com/nl/perl/03012001/
(1): Yes, I made that word up.
(2): I can't say that I'm really doing megaurav2002's question justice here. Question for someone more knowledgeable than I: does %newhash constitute an expression here? I know that in some sense, evaluating a "hash in scalar context" returns "(number of keys in the hash) / (the number of buckets in the table)" and evaluating a "hash in list context" returns the actual keys/values smushed together into a string. However, posts like NEVER a list in a scalar context -- PLEASE! from people like merlyn make me quiver in my boots, so I don't know whether I'm correct to refer to evaluating a "hash in (blank) context".
Edit: Thank you to kyle for a refrence to TFM. I should have R'd it.
|
|---|