加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 21:55:34 所属栏目:大数据 来源:网络整理
导读:最初,我正在使用长度= 2 ^ 16的列表.但是,为了抽象这个,我将在这个例子中设置length = 5. #subroutine to make undefined entries - 0sub zeros { foreach(@_) { if(!defined($_)) { $_ = 0; } }} #print out and indicies and elements of list sub checkin
最初,我正在使用长度= 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 = $countern";
            print "$_n";
            $counter += 1;
        }
            print "n";
    }

方法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

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

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

List = 
index = 0
3
index = 1
0
index = 2
0
index = 3
0
index = 4
5

解决方法

您的方法是正确的,但是您的zeros()函数存在问题.您使用@abc作为参数调用它,该参数生成该列表的副本.然后,您更改副本.在sub的末尾,该副本被丢弃.在check()函数中,您仍在使用原始列表.

你可以像这样解决它:

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

@abc = zeros(@abc);
checking(@abc);

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

如果您使用了严格和警告,它会告诉您:

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.

但是,由于你正在处理一个非常大的数组,我建议使用数组引用,因为复制将是昂贵的.

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

zeros(@abc);
checking(@abc);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读