How can I print undef values as zeros in Perl?
I'm building a count matrix in Perl using AoA开发者_如何学C: 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?
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"
}
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";
}
Just an example, please modify the code to your requirements.
use strict;
use warnings;
my @aoa;
$aoa[1][3]++;
foreach my $i (1 .. 3){
foreach my $j (1 .. 3){
defined $aoa[$i][$j] ? print $aoa[$i][$j] : print "0";
print "\t";
}
print "\n";
}
精彩评论