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
    > that autovivication doesn't happen when you simply check wether a hash key exists or is true.

    unfortunately not that simple!

    use strict; # or die use warnings; # or die my %hash = ( cogito => "ergo sum" # I think, so I exist ); if (exists $hash{absum}{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";
    output
    /usr/bin/perl -w /home/lanx/tst.pl Absum doesn't exist. Keys in the hash: cogito :: absum

    Cheers Rolf

      unfortunately not that simple!

      if (exists $hash{absum}{absum})

      Ah, yes. But note how that syntax implies a -> operator, as ikegami described elsewhere in this thread, and it is that operator which makes $hash{absum} come into existance. Of course it is funny to see how exists still thinks $hash{absum} doesn't exist, however, not so funny anymore when you realize that exists really tries to check the existance of $hash{absum}->{absum} here. So exists is right and the information in that print statement is factually wrong. It should state print "Absum->absum doesn't exist\n" or something similar meaning the same.