perl

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

Solution

  • Just map the undefined value to the string 'undef' like this:

    #! /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>;
    
    my @b1 = map { $_ // 'undef' } @a1;
    my @b2 = map { $_ // 'undef' } @a2;
    my @b3 = map { $_ // 'undef' } @a3;
    
    say "@b1 and @b2 and @b3";
    
    exit(0);