Using grep on undefined array

Abigail abigail at abigail.be
Wed Aug 14 13:12:43 BST 2013


On Wed, Aug 14, 2013 at 08:58:05AM +0100, Matt Freake wrote:
> On Wed, Aug 14, 2013 at 8:40 AM, Mark Overmeer <mark at overmeer.net> wrote:
> 
> > * Andrew Beverley (andy at andybev.com) [130813 23:24]:
> > > Could someone please explain to me why the following outputs an empty
> > > string rather than "*"?
> >
> > @fields != @$fields, which is causing the confusion.
> >
> 
> 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).



Abigail


More information about the london.pm mailing list