Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Yes! This was one of the biggest things I missed when I moved to Ruby. I try and tell people how great autovivification is but unless they've coded with it the feature just sounds strange. But it lets you build some really great data structures on the fly!


I love it as well, and would hate to do without it, but it does come with it's own warts. Such as this:

    use Data::Dumper;
    my %h;
    if ( $h{foo}{bar}{baz} ) { say "Never happens"; }
    say Dumper \%h;
And you get this:

    $VAR1 = {
              'foo' => {
                         'bar' => {}
                       }
            };


You'd want to use the exists operator in that case. It checks if the hash key is present without auto vivifying it.

  my %hash = ();
  if (exists $hash{foo}) {print "This doesn't run!";}


I'm well aware of exists, and how it functions, and that it in no way solves the problem presented. Exists tests for the existence of a hash key, so you can tell if it exists but is possibly undefined, but it does not stop autovivification in any way.

Your example doesn't cause autovivification even without exists. Autovivification is the automatic creation of the underlying hashes and arrays in a multiple level data structure when they are used while accessing a nested data-structure.

For example, given an empty hash %hash, $hash{foo} does not cause autovivification, but $hash{foo}{bar} will automatically create an empty hash and assign a reference to it to $hash{foo}.


Fwiw Perl 6 only autovivifies anything, including intermediary data structure levels, when writing to a data structure. So nothing happens in this case:

  my %h;
  dd %h
  if %h<foo><bar><baz> { say "Never happens" }
  dd %h
prints:

  Hash $var = {}
  Hash $var = {}


Nice, I wasn't aware of that feature, but the features I'm still not aware of in Perl 6 could fill a small book, since I still haven't gotten around to using it for much. :/




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: