At 06:09 PM 6/18/01 -0700, Peter Cornelius wrote:
> > At 04:36 PM 6/18/01 -0700, Peter Cornelius wrote:
> > >use Data::Dumper;
> > >
> > >%hash = (
> > >         1 => "I exist...",
> > >         2 => "This is academic",
> > >         3 => "I should be using an array"
> > >         );
> > >
> > >print Dumper \%hash;
> > >
> > >for $key (keys %hash) {
> > >         $hash{$key++}="Redefined";
> > >         print "$key => $hash{$key}\n";
> > >}
> > >
> > >print Dumper \%hash;
> > >
> > >__output__
> > >$VAR1 = {
> > >           '1' => 'I exist...',
> > >           '2' => 'This is academic',
> > >           '3' => 'I should be using an array'
> > >         };
> > >2 => This is academic
> > >3 => I should be using an array
> > >4 =>
> > >$VAR1 = {
> > >           '1' => 'Redefined',
> > >           '2' => 'Redefined',
> > >           '3' => 'Redefined'
> > >         };
> > >
> > >---Comments--
> > >So the $hash{4} never gets autovivified, even though it's
> > dereferenced,
> >
> > What makes you think it's dereferenced?
>
>
>The '4 => ' line up above from the print statement in the for loop.

Nope, that was you printing it, because $key had been incremented by the 
time your print statement came around, which is why there is no line 
starting 1 => in the output.  So there wasn't any more dereferencing going 
on than if you'd said print $hash{foobar}.  Which is to say, it looks in 
the hash for that key, doesn't find it, returns undef and prints that 
stringified, i.e., nothing.  With -w, an undef use warning.

> >          $hash{$key++} = $value
> >
> > is equivalent to
>...
>
> > Okay?
>
>Yeah, I think that's part of what I was saying in the above.  But also I was
>trying to make sure I understood autoviv.

That ain't autovivification.  This is:

         my %hash;
         $hash{first}{second} = 42;

Now you might think that this is:

         my %hash;
         $hash{foo}++;

But in fact it isn't.  In that case, perl looks in the hash for that key, 
doesn't find it, but the statement is equivalent to

         $hash{foo} = $hash{foo} + 1;

the undef value is returned, coerced to 0 in numeric context, and 
everything works - *except* that because the statement was actually ++, the 
usual warning about use of an uninitialized value is suppressed, because ++ 
is so terribly useful.

>  I had originally thought that
>there was a danger of accidentaly creating a hash entry just by looking at
>it, but from the above code, and a few passages in the camel, I don't think
>testing a hash value will create it.

Only when you have a second level involved, as you say:

>The exception to this would be
>something like $hash{a}{b}, which creates
>$hash{a} if it didn't exist just to test that the b part isn't there.

Sucks somewhat.  May change in a future perl.

--
Peter Scott
Pacific Systems Design Technologies
http://www.perldebugged.com

Reply via email to