Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Why is perl complaining about this?
#!/usr/bin/perl use strict; my $count{'abc'} = 0; print "$count{'abc'}\n";
But this works fine.
my %count; $count{'abc'} = 0;
So, why do I have to define %count? Shouldn't my $count{'abc'} have defined %count for me? Isn't this autovivification?

Replies are listed 'Best First'.
Re: Autovivification Confusion
by toolic (Bishop) on Aug 05, 2011 at 18:27 UTC
    As perl tells you, it is a syntax error. Try this instead:
    my %count = (abc => 0);
    See perldata for ways to initialize a hash.
Re: Autovivification Confusion
by ikegami (Patriarch) on Aug 05, 2011 at 18:31 UTC

    The error you're getting is not because %count doesn't exist.

    $ perl -e'my $count{abc};' syntax error at -e line 1, near "$count{abc" Execution of -e aborted due to compilation errors. $ perl -e'my %count; my $count{abc};' syntax error at -e line 1, near "$count{abc" Execution of -e aborted due to compilation errors.

    Therefore, the issue isn't a lack of autovivification. If it somehow made sense to do my $count{'abc'}, you might be right that %count should be autovivified.

    What you are trying to achieve can be done using

    my %count = ( abc => 0 );
Re: Autovivification Confusion
by Khen1950fx (Canon) on Aug 05, 2011 at 19:04 UTC
    Your first example is a hash slice but no hash was declared. In your second example, you declared the hash, but that's not autovivification. Autovivification is the automatic creation of a variable reference when an undefined value is dereferenced. Maybe this example will help:
    #!/usr/bin/perl use strict; use warnings; use Data::Dumper::Concise; my $hash = { 'foo' => { 'abc' => 0, }, 'bar' => { 'def' => 1, }, }; print Dumper($hash) unless exists $hash->{'baz'}{'ghi'},
    'baz' doesn't exist, so perl creates it---autovivification.

      'baz' doesn't exist, so perl creates it---autovivification.

      In the docs, autovivification refers to the creation of %{ $hash->{'baz'} }, but it's definitely acceptable to consider the creation of $hash->{'baz'} autovivification as well. Both happen here.

Re: Autovivification Confusion
by Anonymous Monk on Aug 05, 2011 at 18:47 UTC
    But shouldn't Perl have interpreted this
    my $count{'abc'};
    as
    my %count = ( 'abc' => undef );
    This is how I understand how autovivification works.

      Yes, if my $count{'abc'}; made sense, that could be an expected result. He had my $count{'abc'} = 0;, though, which is why he's expecting a different result.

      This is how I understand how autovivification works.

      autovivification is the automatic creation of variables when they are needed.

      No part of the OP's file contains code that uses %count (just $count), so it's never needed, so autovivification has nothing to do with the OP's problem.