Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I print undef values as zeros in Perl?

Tags:

undefined

perl

I'm building a count matrix in Perl using AoA: my @aoa = () then call $aoa[$i][$j]++ whenever I need to increment a specific cell. Since some cells are not incremented at all, they are left undef (these are equivalent to 0 counts).

I would like to print some lines from the matrix, but I get errors for undef cells (which I would simply like to print as zeros). what should I do?

like image 311
David B Avatar asked Dec 04 '22 11:12

David B


2 Answers

Use defined with a conditional operator (?:).

#!/usr/bin/perl

use strict;
use warnings;

my @matrix;

for my $i (0 .. 3) {
    for my $j (0 .. 3) {
        if (rand > .5) {
            $matrix[$i][$j]++;
        }
    }
}

for my $aref (@matrix) {
    print join(", ", map { defined() ? $_ : 0 } @{$aref}[0 .. 3]), "\n"
}

If you are using Perl 5.10 or later, you can use the defined-or operator (//).

#!/usr/bin/perl

use 5.012;
use warnings;

my @matrix;

for my $i (0 .. 3) {
    for my $j (0 .. 3) {
        if (rand > .5) {
            $matrix[$i][$j]++;
        }
    }
}

for my $aref (@matrix) {
    print join(", ", map { $_ // 0 } @{$aref}[0 .. 3]), "\n"
}
like image 177
Chas. Owens Avatar answered Dec 22 '22 11:12

Chas. Owens


Classically:

print defined $aoa[$i][$j] ? $aoa[$i][$j] : 0;

Modern Perl (5.10 or later):

print $aoa[$i][$j] // 0;

That is a lot more succinct and Perlish, it has to be said.

Alternatively, run through the matrix before printing, replacing undef with 0.


use strict;
use warnings;

my @aoa = ();

$aoa[1][1] = 1;
$aoa[0][2] = 1;
$aoa[2][1] = 1;

for my $i (0..2)
{
    print join ",", map { $_ // 0 } @{$aoa[$i]}[0..2], "\n";
}
like image 31
Jonathan Leffler Avatar answered Dec 22 '22 09:12

Jonathan Leffler