[英]How can I print undef values as zeros in 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. 我正在使用AoA在Perl中构建一个计数矩阵: my @aoa = ()
然后在需要递增特定单元格时调用$aoa[$i][$j]++
。 Since some cells are not incremented at all, they are left undef
(these are equivalent to 0 counts). 由于某些单元格根本没有增加,因此它们保持undef
(这相当于0计数)。
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). 我想从矩阵中打印一些行,但我得到undef
单元格的错误(我只想将其打印为零)。 what should I do? 我该怎么办?
Use defined
with a conditional operator ( ?:
). 使用条件运算符defined
使用( ?:
。
#!/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 ( //
). 如果您使用的是Perl 5.10或更高版本,则可以使用defined-或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): 现代Perl(5.10或更高版本):
print $aoa[$i][$j] // 0;
That is a lot more succinct and Perlish, it has to be said. 这是更简洁和Perlish,不得不说。
Alternatively, run through the matrix before printing, replacing undef
with 0. 或者,在打印前运行矩阵,将undef
替换为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";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.