Using grep on undefined array

William Blunn at
Wed Aug 14 08:33:27 BST 2013

On 14/08/2013 00:09, Andrew Beverley wrote:
> Could someone please explain to me why the following outputs an empty
> string rather than "*"?

In this case it may be wise to show a “use strict;”, which I assume is 
in effect here, otherwise people can just say that @$a on an undefined 
$a in the absence of "use strict;" would fine anyway.

> get();
> sub get($)
> {   my $fields = shift;
>      my @fields = grep $_ ne 'domain', @$fields;
>      my $select_fields = $fields ? join(',', map { 'users.' . $_ } @fields) : '*';
>      print "$select_fields\n";
> }
> I would have expected $fields to remain undefined, but it seems to be
> turning into an empty array during the grep.

We can write a simpler case to illustrate the point.

This demonstrates the effect of "strict" on @$a when $a is undefined:

     $ perl -E 'use strict; my $a; say @$a;'
     Can't use an undefined value as an ARRAY reference at -e line 1.

but things seem to work differently when @$a an argument to "grep":

     $ perl -E 'use strict; my $a; say grep { 1 } @$a; say $a'


"strict" doesn't appear to apply in this case and @$a appears to be 
being autovivified leaving a reference in $a.

That being the case, I'd also be interested to know why.



More information about the mailing list