How do you print undef elements in an array?

How do you print undef elements in an array?

How do you print "undef" for array elements that are undefined?

#! /usr/bin/env perl

use warnings;
use strict;
use utf8;
use feature qw<say>;

my @a1 = 1..8;
my @a2 = (4143, undef, 8888);
my @a3 = qw<a b c>;

say "@a1 and @a2 and @a3";

exit(0);

This outputs:

Use of uninitialized value $a2[1] in join or string at ./my.pl line 12.
1 2 3 4 5 6 7 8 and 4143  8888 and a b c

But I'd like it to output (without warnings)

1 2 3 4 5 6 7 8 and 4143 undef 8888 and a b c

Answer

One way to print the string "undef" in place of an undefined array item is to check if the item is Read more:

use warnings;
use strict;
use utf8;
use feature qw<say>;

my @a1 = 1..8;
my @a2 = (4143, undef, 8888);
my @a3 = qw<a b c>;

for (@a1, @a2, @a3) {
    $_ = 'undef' unless defined $_;
    print "$_ ";
}

print "\n";

Enjoyed this article?

Check out more content on our blog or follow us on social media.

Browse more articles