in reply to Best Hash Practices?
First things first. ++ for writing a clear and detailed description of your question, including an explanation of why you need it and what your troubles are, without omitting to mention the things you have tried.
That being said, I must add that you should've known your question is based upon wrong assumptions. I won't hold that to you, though, since I'm having a rather hard time too to find the docs that say that autovivication doesn't happen when you simply check wether a hash key exists or is true.
Anyway, I do remember I read it somewhere and I wrote a small script to prove it. Here goes:
use strict; # or die use warnings; # or die my %hash = ( cogito => "ergo sum" # I think, so I exist ); if (exists $hash{absum}) { print "Absum exists."; } else { print "Absum doesn't exist.\n"; # which would explain it's name... } print "Keys in the hash: ", join(" :: ", keys %hash), "\n"; __END__ Absum doesn't exist. Keys in the hash: cogito
So there you have it. As for your second question, simply use a boolean OR.
use strict; use warnings; my %hash = ( list1 => ["foo", "bar", "baz"] ); print "list1: [- ", join(" :: ", @{ $hash{list1} || []}), " -]\n"; print "list2: [- ", join(" :: ", @{ $hash{list2} || []}), " -]\n"; __END__ list1: [- foo :: bar :: baz -] list2: [- -]
Admittedly, that || [] part in there isn't quite a beauty either but it does what you need without too much typing.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Best Hash Practices?
by LanX (Saint) on Oct 09, 2009 at 22:54 UTC | |
by muba (Priest) on Oct 10, 2009 at 02:16 UTC |