you've glimpsed the dark side of autovivification.

when you say unless($apples{$t}{weight})
you're fetching a boolean value.
Perl gives you one free level of autovivification
when you get/fetch a value.
so it autovivifies a hash at key $t when
you try and test for a sub key 'weight'.

as far as I can tell, you MUST first test
for existence of $apples{$t} else you get
one free level of autovivification, and 
it creates an empty hash and then fetches
the value for key 'weight', which is 
undef, which stringifies to ''.

i.e.

foreach my $t (@test)
        {
        next unless(exists($apples{$t}));
        print "$t not found\n" unless $apples{$t}{weight}
        }


greg

Joel Gwynn wrote:
> 
> Wow.  This is driving me crazy.  I'm looking for a value in one of the
> keys in a hash, like so:
> 
> my %apples = (macintosh => {weight => '10lb', cost => '5'},
>               red_delicious => {weight => '15lb', cost => '2'},
>               fuji => {weight => '12lb', cost => '7'});
> 
> my @test = qw(granny_smith crabapple);
> 
> foreach my $t (@test){ print "$t not found\n" unless $apples{$t}{weight}
> } print "\n-----------------------\n"; foreach my $a (keys %apples){
>     print "$a: weight: $apples{$a}{weight}\n";
> }
> 
> And what I get output is this:
> 
> granny_smith not found
> crabapple not found
> 
> -----------------------
> granny_smith: weight:
> fuji: weight: 12lb
> crabapple: weight:
> red_delicious: weight: 15lb
> macintosh: weight: 10lb
> 
> Now, what's driving me crazy is that the two test values are being added
> to the hash, simply by looking for $apples{$t}{weight}.  If I simply
> look for $apples{$t}, like so:
> 
> foreach my $t (@test){ print "$t not found\n" unless $apples{$t} }
> 
> new hash members are not created.  Why should this be?
> 
> _______________________________________________
> Boston-pm mailing list
> [EMAIL PROTECTED]
> http://mail.pm.org/mailman/listinfo/boston-pm

-- 
Greg London
x7541


            \|/ ____ \|/
            ~@-/ oO \-@~
            /_( \__/ )_\
               \__U_/
_______________________________________________
Boston-pm mailing list
[EMAIL PROTECTED]
http://mail.pm.org/mailman/listinfo/boston-pm

Reply via email to