Autovivification

Autovivification is a Perl term, stated if a variable hasn’t been created before being used by a function, then it will initialised as undef which means undefined. If such variable is being used in a function, it will be converted into 0 or an empty string (““), which means false# in Perl, depending on the context. It can be a good thing to have, but it is not for all situations. It is suggested to import standard libraries warnings and strict to show undefined variables as warnings when interpreted by Perl.

Links to this page
  • Perl Reference

    As shown, a Reference will be Autovivified# into string, which means that it can’t point to a string as it is a string itself. If it is evaluated, it will always return true#. To dereference it, we could add an extra $ to the reference:

  • Perl Hash

    To get the value of the key from the hash, using the “$” sigil and the following syntax. However if the key hasn’t been created before this, undef# will be returned.

    We can also test whether the key specified exists in the Perl Hash using the function exist(). However, keep in mind that it doesn’t work well with multi-level hash verification, that is there is a hash table contained in another hash table. Perl will autovivify# all the lower-level keys and will not check the validity of the higher-level key. Therefore, it is recommended to test the key individually, level by level, from high to low, in order to prevent such bug from happening.

  • Perl Boolean

    Note: If the subroutine (sub) doesn’t return a value such as the following, then Perl will think that it is returning a false value due to #Autovivification. Which type of the value should it return is depending on where does the value is being used.

  • Perl Array

    Note: Either case, the length or the total number of elements of a Perl Array does count undef# as a valid member. Therefore, it shouldn’t surprise you if the above-mentioned methods count undef elements in the total number of elements inside the array.

#perl