Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you print undef elements in an array?

Tags:

perl

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

2 Answers

Install and use Data::Printer, it prints Perl variables in a nice, human readable format:

use Data::Printer;

my @a = (1,2,3,undef,4);

p @a;

Prints:

[
    [0] 1,
    [1] 2,
    [2] 3,
    [3] undef,
    [4] 4
]
like image 179
Rawley Fowler Avatar answered Apr 30 '26 18:04

Rawley Fowler


I would ditch the array interpolation and do

say join ' and ',
    join($", map $_//'undef', @a1),
    join($", map $_//'undef', @a2),
    join($", map $_//'undef', @a3);

($" is what array interpolation uses between elements, if you expect it to be ' ', just use that instead.)

or avoid the repetition with:

say join ' and ',
    map
        join($", map $_//'undef', @$_),
        \(@a1, @a2, @a3);
like image 24
ysth Avatar answered Apr 30 '26 20:04

ysth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!