http://www.perlmonks.org?node_id=659440


in reply to Why does exists cause autovivication?

This node falls below the community's threshold of quality. You may see it by logging in.
  • Comment on Re: Why does exists cause autovivication?

Replies are listed 'Best First'.
Re^2: Why does exists cause autovivication?
by Jenda (Abbot) on Dec 29, 2007 at 14:48 UTC

    Let me see ... how many times have I spent time hunting a bug caused by autovivification during my ten years with Perl ... zero. How many times did it save me from code like if($data and $data->{foo} and $data->{foo}{bar} and $data->{foo}{bar}{baz} and $data->{foo}{bar}{baz}{bat}) or

    if (!exists($data->{$key}) { $data->{$key} = []; } push @{$data->{$key}}, $new_value;
    ? Countless.

    If you hear about autovivification for the first time it may sound scary, but you do get used to it. And the problems caused by autovivification are few and far apart.

Re^2: Why does exists cause autovivication?
by demerphq (Chancellor) on Dec 29, 2007 at 14:17 UTC

    Oh how ye discredit thyself! Auto-viv is much more useful than you make it sound and it only rarely causes problems, usually because someone hasn't managed to understand how it works.

    ---
    $world=~s/war/peace/g

      Thy careless writing, brother, doth bring pain unto mine eyes, for verily thou mixest the high and low modes of address, like unto a novice that mistaketh his sigils, as "@foo[0]" &c. Wherefore I commend unto thee that when thou wouldst chastise thy brethren so, thou shouldst say instead "How thou discreditest thyself", or "how ye discredit yourself".

      I think I agree with your point, though. Autovivification is one of those features that's both a strength and a weakness of Perl. A strength, because it's a very practical feature that makes life a bit easier for you and me; a weakness, because people who suffer from a surfeit of the wrong sort of laziness use it as an example of how Perl is "too hard".

        Whoops! :-) Thanks for the correction. (And ++ for style :-)

        ---
        $world=~s/war/peace/g

        Even the Perl people call autovivication - specifically when using exists - surprising behaviour:

        exists

        Near the bottom:
        "This surprising autovivification in what does not at first--or even second--glance appear to be an lvalue context may be fixed in a future release."

        I would not expect something that just returns true or false to modify the data that is passed to it. I know that people are going to say that it is not modifying the data passed to it - because you are actually dereferencing the hash elements in the CALL to exists() - not within exists itself. However, there must be some way to prevent it from happening when calling exists(). If any one of the lower hash keys does not exist in the hash being tested, then obviously the one you're testing for does not, and exists() should just return false.