Using grep on undefined array

Matt Lawrence matt.lawrence at
Wed Aug 14 13:59:08 BST 2013

On 14/08/13 13:12, Abigail wrote:
> On Wed, Aug 14, 2013 at 08:58:05AM +0100, Matt Freake wrote:
>> I don't think the original poster is confusing those two, and when I
>> applied 'use strict' to the original code (with the sub) it didn't help (no
>> warnings or errors). The bit I'm stuck on is why does
>>     my @fields = grep($_ ne 'domain', @$fields);
>> autovivify $fields but
>>     my @fields = @$fields;
>> does not.
> My guess: it's an unintentional side-effect of $_ being an alias in the
> first argument of grep.
> Someone else mentioned that autovivification only happens in lvalue context,
> but that isn't true:
>      $ perl -E 'my $a; $$a {foo}; say $a; say keys %$a;
>                        $$a {bar} {baz}; say keys %$a'
>      HASH(0x100802cb8)
>      bar
>      $
> The first use autovivifies an empty hash; the second use autovivifies
> the key 'bar' (and a reference to an empty hash as value).

It seems I got this idea from the docs:

man perlref:

This is one of the cases we mentioned earlier in which references could 
spring into existence when in an lvalue context.

man perlglossary:


A Graeco-Roman word meaning “to bring oneself to life”. In Perl, storage 
locations (lvalues) spontaneously generate themselves as needed, 
including the creation of any hard reference values to point to the next 
level of storage. The assignment $a[5][5][5][5][5] = "quintet" 
potentially creates five scalar storage locations, plus four references 
(in the first four scalar locations) pointing to four new anonymous 
arrays (to hold the last four scalar locations). But the point of 
autovivification is that you don’t have to worry about it.

I note there's a difference between accessing an element of a structure 
and accessing the structure itself:

$ perl -Mstrict -E 'my $foo; %$foo'
Can't use an undefined value as a HASH reference at -e line 1.

I haven't been able to find any circumstances in which accessing an 
element doesn't autovivify. Perhaps element access is a special form of 
lvalue context? *shrug*


More information about the mailing list