Using grep on undefined array
Adrian Lai
perl at loathe.me.uk
Wed Aug 14 01:17:33 BST 2013
On 14 August 2013 00:09, Andrew Beverley <andy at andybev.com> wrote:
> Hi,
>
> Could someone please explain to me why the following outputs an empty
> string rather than "*"?
>
> 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.
>
> I've discovered that I can make it work by conditionally declaring
> @fields (with "if $fields"), but I'd still like to know what's going on
> here.
>
> Thanks,
>
> Andy
The use of @$fields is sufficient to autovivify $fields as an array ref.
As such, it's defined when you come to check it within your ternary.
Perhaps "my $select_fields = @$fields ? ..." would work for you? It's
not quite the same result as you'd get by conditionally declaring
@fields (you'd get "*" returned if you passed in an empty array ref
(i.e. get([])) rather than "").
Alternatively I'd suggest restructuring to return early in the case of
$fields being undef.
Adrian.
More information about the london.pm
mailing list