0

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?

3
  • Re "But, this doesn't catch the value.", undef doesn't check if something is undefined; it makes things undefined and/or returns an undefined scalar (depending on how it's used) Commented Nov 5, 2020 at 19:15
  • Re "even when I have use autodie ':all' set", push can't fail, so the concept of making it die on failure makes no sense. Commented Nov 5, 2020 at 19:20
  • Proper code construction is next unless defined $var; Commented Nov 5, 2020 at 20:43

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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);

Comments

2

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
        ];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.