Brian Ling wrote: > my $test1 = ${refer}->{value}->{fred}; > print Dumper($refer); > # this doesn't change the data as i'd expect > > my $test2 = ${refer}->{value}->{fred}->{value}; > print Dumper($refer); > # this actually creates a key 'fred' pointing > # to a empty hash ref #I > > So my question really has two parts. > > Why does the above actually change the data, any > pointers to reading material would be great. I've read > a bit about autovification, is that what's going on. > If so, how is this happening with an "assignment" or > an "if".
> my $test1 = ${refer}->{value}->{fred}; Perl does not autovivify $refer->{value}{fred}. Read perlfaq4: "Why does passing a subroutine an undefined element in a hash create it?" "Normally, merely accessing a key's value for a nonexistent key does not cause that key to be forever there." > my $test2 = ${refer}->{value}->{fred}->{value}; Here we are looking for a key's value. Perl does not autovivify that key, but it does autovivify $refer->{value}{fred} as expected. > Given that I have a data structure similar to the > above (returned from a module), of which I don't > know the exact shape. How do I test for the > existence of a key, down a branch without > changing the data. All I could come up with is: > > if (${refer}->{value}->{fred} ) { > my $test3 = ${refer}->{value}->{fred}->{value} > } > > As I know if fred exists there will be a key called > value, and testing for fred doesn't change my data. > Is there a better way of doing this? Read 'perlfunc' for details about the 'exists' function. I would still test $refer->{value}{fred}{value}. if ( exists $refer->{value}{fred} and exists $refer->{value}{fred}{value} ) { my $test3 = $refer->{value}{fred}{value}; } OR: my $test3 = $refer->{value}{fred}{value} if exists $refer->{value}{fred} and exists $refer->{value}{fred}{value}; HTH, Charles K. Clarkson -- Mobile Homes Specialist 254 968-8328 -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>