如何获取列表以在Perl中显示空条目的零?

myn*_*EFF 7 perl

最初,我正在使用长度= 2 ^ 16的列表.但是,为了抽象这个,我将在这个例子中设置length = 5.

#subroutine to make undefined entries -> 0
sub zeros {
    foreach(@_) {
        if(!defined($_))    {
            $_ = 0;
        }
    }
}       
 #print out and indicies and elements of list 
    sub checking {
        print "List = \n";
        my $counter = 0;
        foreach (@_) { 
            print "index = $counter\n";
            print "$_\n";
            $counter += 1;
        }
            print "\n";
    }
Run Code Online (Sandbox Code Playgroud)

方法1:如果我访问不同的索引来编辑元素,我打印出数组时会得到以下内容.我不想看到空白.我希望他们是0.我已经设置了一个子程序"零",使未定义的条目变为零.但我不知道我的代码出了什么问题.我还为列表的每个元素尝试了"$ _ + = 0".我仍然无法为空条目获取零.

#method 1
@abc = ();
$abc[1] = 3;
$abc[5] = 5;
&zeros(@abc);
&checking(@abc);
List = 
index = 0

index = 1
3
index = 2

index = 3

index = 4

index = 5
5
Run Code Online (Sandbox Code Playgroud)

方法2:我可以得到零,如果我初始化列表这样.但正如我所说,我正在处理很长的列表,我不能绝对不会像这样初始化我的列表.

#method 2
@abc = (3,0,0,0,5);
&checking(@abc);

List = 
index = 0
3
index = 1
0
index = 2
0
index = 3
0
index = 4
5
Run Code Online (Sandbox Code Playgroud)

sim*_*que 4

你的方法是正确的,但是你的功能有问题zeros()。您将其@abc作为参数调用,这会生成该列表的副本。然后您更改副本。在子程序结束时,该副本将被丢弃。在您的checking()函数中,您仍在使用原始列表。

你可以这样修复它:

sub zeros {
  my @list = @_;
  @list = map { $_ // 0 } @list;
  return @list;
} 

@abc = zeros(@abc);
checking(@abc);
Run Code Online (Sandbox Code Playgroud)

诀窍是返回更改后的列表并将其重新分配给原始变量。

如果您使用过strictwarnings它会告诉您:

Use of uninitialized value $_ in concatenation (.) or string at F:\scratch.pl line 28. List =  index = 0

index = 1 3 index = 2

index = 3

index = 4

index = 5 5

Use of uninitialized value $_ in concatenation (.) or string at F:\scratch.pl line 28. 
Use of uninitialized value $_ in concatenation (.) or string at F:\scratch.pl line 28. 
Use of uninitialized value $_ in concatenation (.) or string at F:\scratch.pl line 28.
Run Code Online (Sandbox Code Playgroud)

但由于您正在处理一个非常大的数组,我建议使用数组引用,因为复制会很昂贵。

sub zeros {
  $_ //= 0 for @{ $_[0] };
} 

zeros(\@abc);
checking(@abc);
Run Code Online (Sandbox Code Playgroud)