On 4/5/06 Stewart Leicester wrote:
>Bruce Van Allen wrote:
>>Both
>>     defined $phash{"D"}[3]
>>and
>>     exists $phash{"D"}[3]
>>
>>autovivify $phash{"D"}.
>>
>>- Bruce
>
>'defined' will autovivify, 'exists' will not. I'll leave it up to 
>Doug to decide if knowing that helps.

Oh? Try this:

#!/usr/bin/perl -w

use strict;

my %hash    = (
    A   => [qw/a0 a1 a2/],
);

# $hash{A}
if (defined $hash{A}[2]) {
    print "OK \$hash{A}[2] defined\n"
}
if (exists $hash{A}[2]) {
    print "OK \$hash{A}[2] exists\n"
}

# test defined() on $hash{B}
if (defined $hash{B}[2]) {
    print "OK \$hash{B}[2] defined\n"
} elsif (exists $hash{B}) {
    print "OK \$hash{B} exists: autovivified from defined()\n"
}

# test exists() on $hash{D}
if (exists $hash{D}[2]) {
    print "OK \$hash{D}[2] exists\n"
} elsif (exists $hash{D}) {
    print "OK \$hash{D} exists: autovivified from exists()\n"
}

__END__

prints:
OK $hash{A}[2] defined
OK $hash{A}[2] exists
OK $hash{B} exists: autovivified from defined()
OK $hash{D} exists: autovivified from exists()


The autovivification is happening when the values are dereferenced.

The expression
    exists $hash{D}[2]
is testing the existence of the third element in the array ref
ostensibly stored in $hash{D}, so $hash{D} gets autovivified to allow
the test.


1;

- Bruce

__bruce__van_allen__santa_cruz__ca__

Reply via email to