Using grep on undefined array
Mark Overmeer
mark at overmeer.net
Wed Aug 14 08:40:57 BST 2013
* Andrew Beverley (andy at andybev.com) [130813 23:24]:
> 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) : '*';
I expect you would like to see the samen result when $fields is undef or
and empty ARRAY, so the answer on the first question is probably a bug:
you check for the existence of $fields, where you probably mean @fields.
my $select_fields = @fields ? join(',', map { 'users.' . $_ } @fields) : '*';
my $select_fields = @fields ? join(',', map "users.$_", @fields) : '*';
@fields != @$fields, which is causing the confusion.
my @users = grep $_ ne 'domain', @$fields;
my $select_users = @users ? join(',', map "users.$_", @users) : '*';
> I would have expected $fields to remain undefined, but it seems to be
> turning into an empty array during the grep.
Autovivification: you tell Perl that the undefined $fields is an ARRAY,
so it conforms to that.
--
Regards,
MarkOv
------------------------------------------------------------------------
Mark Overmeer MSc MARKOV Solutions
Mark at Overmeer.net solutions at overmeer.net
http://Mark.Overmeer.net http://solutions.overmeer.net
More information about the london.pm
mailing list