con
con

Reputation: 6093

How to grep undefined values in an array?

I have an array with an undefined value:

[0] 0.1431,
[1] undef

I then later push this value onto an array, and Perl doesn't warn me about the uninitialized values (I cannot imagine why someone would want this to happen without a warning or die, even when I have use autodie ':all' set, but that's another story)

So I try and grep on these arrays to prevent pushing undef values onto arrays, thus:

if (grep {undef} @array) {
    next
}

But, this doesn't catch the value.

How can I grep for undefined values in Perl5?

Upvotes: 0

Views: 455

Answers (3)

ikegami
ikegami

Reputation: 385496

Why not prevent the values from being added in the first place?

Replace

push @array, LIST;

with

push @array, grep defined, LIST;

If it's specifically a scalar, you could also use

push @array, $scalar if defined($scalar);

Upvotes: 3

toolic
toolic

Reputation: 61937

You can use defined to get rid of undefined items:

use warnings;
use strict;
use Data::Dumper;

my @a1 = (1,2,3,undef,undef,4);
print Dumper(\@a1);

my @a2 = grep { defined } @a1;
print Dumper(\@a2);

Output:

$VAR1 = [
          1,
          2,
          3,
          undef,
          undef,
          4
        ];
$VAR1 = [
          1,
          2,
          3,
          4
        ];

Upvotes: 2

stevieb
stevieb

Reputation: 9296

grep for not defined instead:

use warnings;
use strict;

my @array = (0, undef, undef, 3);

if (grep {! defined} @array) {
    print "undefined values in array\n";
}

There are several reasons as to why you'd want to have/allow undefined values in an array. One such beneficial scenario is when passing in positional parameters to a function.

Upvotes: 5

Related Questions